这是一种通过 Python 的符号数学库 sympy 实现的方法。
作为一个例子,我们试图找到第一个n 三角数之和的公式。三角数(公式n*(n+1)/2)是0, 1, 3, 6, 10, 15, 21, ....。因此,第一个n 三角数的总和是0, 1, 4, 10, 20, 35, 56, ...。
from sympy import Eq, solve
from sympy.abc import a,b,c,d, x
formula = a*x**3 + b*x**2 + c*x + d # general cubic formula
xs = [0, 1, 2, 3] # some x values
fxs = [0, 1, 4, 10] # the corresponding function values
sol = solve([Eq(formula.subs(x, xi), fx) for xi, fx in zip(xs, fxs)])
print(sol) # {a: 1/6, b: 1/2, c: 1/3, d: 0}
您可以使用更多 x、fx 对来检查三次公式是否足够(这不适用于浮点值,因为 sympy 需要精确的符号方程)。
sympy 的interpolate 也很有趣。这通过一些给定的点计算多项式。这样的代码可能如下所示:
from sympy import interpolate
from sympy.abc import x
xs = [0, 1, 2, 3]
fxs = [0, 1, 4, 10]
fx_dict = dict(zip(xs, fxs))
sol = interpolate(fx_dict, x)
print(sol) # x**3/6 + x**2/2 + x/3
print(sol.factor()) # x*(x + 1)*(x + 2)/6