![](/img/trans.png)
[英]How to solve a cubic function with more than hundred pairs of known dependent and independent variable in python
[英]How to solve a cubic function without knowing the coefficients a b and c?
為這個愚蠢的問題道歉。 在下面的 cubie 函數中(來自學校項目),我得到了 x 和 f(x) 的值,而系數 a、b、c 和 d 的常數是未知的。
f(x)=ax^3+bx^2+cx+d
在這種情況下,有沒有辦法通過使用任何 python 包找出 a、b 和 c? 我找到了大量用於求解三次函數的 python 教程,但它們似乎主要集中在求解 x 而給出了 a、b 和 c 值。
這是一種通過sympy的方法,Python 的符號數學庫。
例如,我們試圖找到前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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.