首页 > 解决方案 > 为随机输入生成随机多项式

问题描述

我目前正在研究 python 的 polyfit 库。我确实有一个特定的输入值A和一个期望的输出值B。我想生成一个复杂度为 5 <= n <= 10 的随机多项式,当给定 A 作为输入时,B 作为解决方案。实现这一目标的最佳方法是什么?

标签: pythonpolynomials

解决方案


正如我在评论中建议的那样,如果您只需要拟合一个值,您可以为所有系数选择任意值,然后调整最终系数,使曲线通过您想要的点。这基本上相当于在图形上画一条曲线,然后向上或向下滑动,直到它与所需的点相交。

import random

def generate_polynomial(degree, a, b):
    """chooses coefficients for a polynomial of the given degree, such that f(a) == b"""

    #to fit only one data point, we can choose arbitrary values for every coefficient except one, which we initially set to zero.
    coefficients = [0] + [random.randint(1, 10) for _ in range(degree-1)]

    #now calculate f(a). This will probably not be equal to b, initially.
    y = sum(coefficient * a**n for n, coefficient in enumerate(coefficients))

    #setting the final coefficient to their difference will cause f(a) to equal b.
    coefficients[0] = b - y

    return coefficients

seq = generate_polynomial(3, 4, 42)
print(seq)

一种可能的结果:

[-18, 7, 2]

这对应于f(x) == 2*x^2 + 7*x - 18。用手很容易确认 f(4) == 2*16 + 7*4 - 18 = 42。


推荐阅读