曲线拟合与python错误
作者:互联网
我正在尝试将数据拟合为(cos(x))^ n.理论上n的值为2,但我的数据应为1.7.当我定义拟合函数并尝试curve_fit时,出现错误
def f(x,a,b,c):
return a+b*np.power(np.cos(x),c)
param, extras = curve_fit(f, x, y)
这是我的资料
x y error
90 3.3888756187 1.8408898986
60 2.7662844365 1.6632150903
45 2.137309503 1.4619540017
30 1.5256883339 1.2351875703
0 1.4665463518 1.2110104672
错误看起来像这样:
/usr/local/lib/python3.5/dist-packages/ipykernel_launcher.py:4:
RuntimeWarning: invalid value encountered in power after removing
the cwd from sys.path./usr/lib/python3/dist-packages/scipy/optimize/minpack.py:690:
OptimizeWarning: Covariance of the parameters could not be estimated
category=OptimizeWarning)
解决方法:
问题在于cos(x)可以变为负数,然后cos(x)^ n可以不确定.插图:
np.cos(90)
-0.44807361612917013
和例如
np.cos(90) ** 1.7
nan
这会导致您收到两条错误消息.
如果您修改模型,例如到a b * np.cos(c * x d).然后该图如下所示:
可以在下面找到一些内联注释的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def f(x, a, b, c, d):
return a + b * np.cos(c * x + d)
# your data
xdata = [90, 60, 45, 30, 0]
ydata = [3.3888756187, 2.7662844365, 2.137309503, 1.5256883339, 1.4665463518]
# plot data
plt.plot(xdata, ydata, 'bo', label='data')
# fit the data
popt, pcov = curve_fit(f, xdata, ydata, p0=[3., .5, 0.1, 10.])
# plot the result
xdata_new = np.linspace(0, 100, 200)
plt.plot(xdata_new, f(xdata_new, *popt), 'r-', label='fit')
plt.legend(loc='best')
plt.show()
标签:scipy,curve-fitting,scientific-computing,function-fitting,python 来源: https://codeday.me/bug/20191026/1933871.html