Reputation: 111
I am trying to curve fit my data with scipy.optimize.curve_fit. For some reason it doesn't like my equation. If I plot the equation using plausible numbers it looks right. So I trust my equation. If I try to fit to a simpler equation, it works, so I trust my code in general. Any advice as to why it doesn't work? The specific error return is "Residuals are not finite in the initial point." Changing p0 to anything reasonable is also unhelpful
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import numpy as np
Y=np.array([0.00001,1.421828697,2.553970883,3.340262844,3.931459808,
4.640896164,5.084293887,5.379892368,5.557251457,5.705050698,
5.823290091,5.911969636,5.971089332,6.059768876,6.118888573,6.178008269,
6.266687814])
X=np.array([0,2500,5000,7500,10000,15000,20000,25000,
30000,35000,40000,45000,50000,55000,60000,65000,70000])
plt.plot(X,Y,'g^')
def func(X,J,g):
u=6.720*10**-5
k=1.380*(10**-16)
T=2
N=1
x=g*J*u*(X)/(k*T)
return N*g*J*(((2*J+1)/(2*J))*(1/(np.tanh((2*J+1)*x/(2*J))))-(1/(2*J))*
(1/(np.tanh(x/(2*J)))))
plt.figure(1)
popt, pcov = curve_fit(func, X,Y,p0=[3.5,2],bounds=([0.25,0.001],[10,4]))
plt.plot(X, func(X, *popt), 'r--', label='fit-with-bounds')
print(" J is %s " %(popt[0]),"\n","g is %s" %(popt[1]))
Upvotes: 0
Views: 2554
Reputation: 4657
You include an X value of exactly zero, causing divide-by-zero errors. If I replace the value of zero with 0.01 your code works in my tests.
Upvotes: 1