我目前正在研究python的polyfit库。
我确实有一个特定的输入值A
和一个期望的输出值B
。我想生成一个复杂度为5 <= n <= 10的随机多项式,当给定A作为输入时,将B作为解决方案。
最好的方法是什么?
答案 0 :(得分:2)
正如我在评论中建议的那样,如果只需要拟合一个值,则可以为所有系数选择任意值,然后调整最终系数,以使曲线穿过所需的点。从根本上讲,这等效于在图形上绘制曲线,然后向上或向下滑动直到与所需的点相交。
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很容易。