function() 采用 4 个位置参数,但 5 个是 given_def Python 3.5 中的函数
function() takes 4 positional arguments but 5 were given_def function in Python 3.5
我正在尝试从我的数据中拟合指数函数。我对将数学函数拟合到我的数据还不是很有经验。
下面是我现在的代码。
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
my_x = (4,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40)
my_y = (0.022172333,0.020881,0.017729,0.021641333,0.02479,0.030755667,0.037235,0.048389,0.068451,0.06898974,0.161409,0.242802333,0.316012667,0.440762333,0.569118333,0.7016839,0.832527333)
def myfunc(x,a,b,c):
return a*np.exp(b*x)+c
p=[my_x,0.0045,0.1262,0] #pre-determined a=0.0045, b=0.1262, c=0 according to excel
popt, pcov = curve_fit(myfunc,my_x,my_y, p0=p)
plt.plot (my_x,myfunc(my_x, *popt))
我收到的错误消息如下。
return function(xdata, *params) - ydata
TypeError: myfunc() takes 4 positional arguments but 5 were given
我认为我不太理解此错误消息的含义。谁能帮助我了解导致此错误的原因以及如何改进我的代码?
myfunc
函数接收四个参数,x
、a
、b
和c
。
错误信息说你提供了5个参数。这是因为您解压了 popt
,它可能包含四个元素(因此解压时有四个参数)。
这一行:
plt.plot (my_x,myfunc(my_x, *popt))
myfunc
函数接收my_x
+四个参数。
它有五个参数,但函数只需要四个。
关于拆包的更多信息here。
我正在尝试从我的数据中拟合指数函数。我对将数学函数拟合到我的数据还不是很有经验。 下面是我现在的代码。
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
my_x = (4,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40)
my_y = (0.022172333,0.020881,0.017729,0.021641333,0.02479,0.030755667,0.037235,0.048389,0.068451,0.06898974,0.161409,0.242802333,0.316012667,0.440762333,0.569118333,0.7016839,0.832527333)
def myfunc(x,a,b,c):
return a*np.exp(b*x)+c
p=[my_x,0.0045,0.1262,0] #pre-determined a=0.0045, b=0.1262, c=0 according to excel
popt, pcov = curve_fit(myfunc,my_x,my_y, p0=p)
plt.plot (my_x,myfunc(my_x, *popt))
我收到的错误消息如下。
return function(xdata, *params) - ydata
TypeError: myfunc() takes 4 positional arguments but 5 were given
我认为我不太理解此错误消息的含义。谁能帮助我了解导致此错误的原因以及如何改进我的代码?
myfunc
函数接收四个参数,x
、a
、b
和c
。
错误信息说你提供了5个参数。这是因为您解压了 popt
,它可能包含四个元素(因此解压时有四个参数)。
这一行:
plt.plot (my_x,myfunc(my_x, *popt))
myfunc
函数接收my_x
+四个参数。
它有五个参数,但函数只需要四个。
关于拆包的更多信息here。