user7852656 user7852656 - 2 months ago 37
Python Question

function() takes 4 positional arguments but 5 were given_def function in Python 3.5

I am trying to fit exponential function from my data. I am not very experienced with fitting mathematical functions to my data yet.
Below is my code right now.

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))


The error message that I get is the following.

return function(xdata, *params) - ydata

TypeError: myfunc() takes 4 positional arguments but 5 were given


I don't think I am quite understanding what this error message is saying. Could anyone help me understand what is causing this error and how I could improve my code?

Answer Source

The myfunc function receive four parameters, x, a, b and c.

The error message says that you provided 5 parameters. It's because you unpacked popt who probably contains fours elements (and thus four paramaters while unpacking it).

In this line:

plt.plot (my_x,myfunc(my_x, *popt))

The myfunc function receive my_x + four parameters. It makes five parameters but the function only wants four.

More about unpacking here.