gpt4 book ai didi

Python通过特定多项式进行曲线拟合

转载 作者:行者123 更新时间:2023-12-01 09:00:10 28 4
gpt4 key购买 nike

我有一个关于Python曲线拟合的问题,我知道 numpy 中有 polyfit 函数,但是如果我将多项式指定为AX^4 + BX^2,如何找到这个A和B???

import numpy as np
import matplotlib.pyplot as plt

points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
z = np.polyfit(x, y, 4) <---?
f = np.poly1d(z) <---?

谁能给点提示吗???谢谢!

最佳答案

您可以尝试使用最小二乘法。基本上找到值 A 和 B,使残差平方和最小。我为此使用了 scipy。

这是我的代码:

import numpy as np
from scipy.optimize import leastsq
# --------------------------------
import matplotlib as mpl
mpl.rcParams['font.size']=20
import matplotlib.pyplot as plt
# -------------------------------------
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]

# calculate polynomial
#z = np.polyfit(x, y, 4) <---?
#f = np.poly1d(z) <---?
# ----------------------------------------------
def poly(p,x):
return p[0]*x**4+p[1]*x**2

def res(p,x,y):
return y-poly(p,x)
# ----------------------------------------------
p0=[1.,1.];
pars=leastsq(res,p0,(x,y));
print pars[0]
# -----------------------------------------------
xi=np.linspace(np.min(x),np.max(x),100);

fig = plt.figure(figsize=(6,6));ax=fig.add_subplot(111);
ax.plot(x,y,ms=10,color='k',ls='none',marker='.');
ax.plot(xi,poly(pars[0],xi),color='0.8',lw=2.0);
plt.savefig('fit_result.png');
plt.show();

关于Python通过特定多项式进行曲线拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52518662/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com