I have two arrays of data, on which I need to fit a nonlinear curve. I am using scipy.optimize and it returns such odd results that when I plot it next to my data points, the curve looks completely wrong. I haven’t found anything useful on stackoverflow or youtube and this is my last resort.
I am trying to fit a curve of the shape y = Asin^2(Bx^2 + C/2)
on my data points.
My current code looks like this:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
I3 = np.array([12.5, 73.2, 99.5, 96.8, 73.2, 50, 27.1, 10.6, 3.1, 1.31, 0.40, 0.33, 0.41, 0.47, 0.55, 0.56, 0.55, 0.54])
U = np.array([951, 888, 808, 737, 683, 639, 581, 508, 437, 392, 232, 255, 201, 166, 93, 68, 4.5, 3.4])
def fit_func3(x, a, b, c):
return a * (np.sin(b* x ** 2) + c/2) ** 2
popt, _ = curve_fit(fit_func3, U, I3)
a, b, c = popt
I3_fit = fit_func3(U, a, b, c)
plt.xlabel('Voltage [$mu$V]')
plt.ylabel('Current [$mu$A]')
plt.plot(U, I3_fit, color='red', label=f'y = I$_0$ sin$^2$($pi$BLU$^2$/d$^2$ + C/2)')
plt.scatter(U, I3, color='black', label='podatki')
plt.errorbar(U, I3, xerr=U_err, yerr=I3_err, fmt='o', capsize=5, color='black')
plt.legend(loc='upper left')
plt.savefig('graph3.png')
plt.show()
The resulting curve looks like this:
enter image description here
I know that a normal y = sin^2(x^2)
looks very close to the data points, but somehow the fitting doesn’t work properly. I haven’t found any ways to limit the domain so that the data would fit properly.
I even tried to artificially add data points in order to increase the quality of the fit, but it only made it slightly less messy and wild(if this is even helpful to post here):
I3_fill = []
U_fill = []
for i in range(len(I3) - 1):
I3_fill.extend(np.linspace(I3[i], I3[i+1], 12)[0:-1])
U_fill.extend(np.linspace(U[i], U[i+1], 12)[0:-1])
I3_fill.append(I3[-1])
U_fill.append(U[-1])
I3_fill = np.array(I3_fill)
U_fill = np.array(U_fill)
I also tried reducing the parameters to only 2 as in y = a * (np.sin(b * x ** 2)) ** 2
, but it didn’t help at all.
I have tried 2 online fitting tools, and they returned the same result no matter how I tinkered with them.
I am guessing the method scipy uses for optimization is not good in this case?
Svit Mlinar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.