Reputation: 11
I am trying to write a code in python that fit a sum of exponetials to some data. However I want to have the freedom to choose how many exponetials I use.
def fcn(x,nexp):
return sum(ai * np.exp(-Ei * x) for ai, Ei in range(nexp))
I have tried to define the above and then call it inside scipy.optimize.curve_fit but I get the error "'int' object is not iterable". Any help would greatly be appreciated. At the moment I just keep defining new functions and adding terms as follow
def f1(t,a1,E1):
return a1*np.exp(-E1*t)
def f2(t,a1,E1,a2,E2):
return a1*np.exp(-E1*t)+a2*np.exp(-E2*t)
def f3(t,a1,E1,a2,E2,a3,E3):
return a1*np.exp(-E1*t)+a2*np.exp(-E2*t)+a3*np.exp(-E3*t)
def f4(t,a1,E1,a2,E2,a3,E3,a4,E4):
return a1*np.exp(-E1*t)+a2*np.exp(-E2*t)+a3*np.exp(-E3*t)+a4*np.exp(-E3*t)
Upvotes: 1
Views: 98
Reputation: 724
Instead of passing each a1, E1
as separate arguments, you could have one function that accepts a list of two-tuples (e.g. [(a1,E1),(a2,E2)]
)then iterate through.
def f(t, lst):
sum = 0
for a, E in lst:
sum += a*np.exp(-E*t)
return sum
This could be written shorter, I gave it step-by-step for clarity.
Upvotes: 3