Use Of Curve_fit To Fit Data Of 2 Variables In A List
I am kind of new to scipy and curve_fit. I have 2 lists: x values: [0.723938224, 0.965250965, 1.206563707, 1.447876448, 1.689189189, 1.930501931, 2.171814672] y values: [2.758, 2
Solution 1:
For a start, let's define the curve fit function. You say that Excel tells you the function is of the form a/(b*(x/c)**d)
. I tell you, Excel knows nothing about anything apart from autofill; this equation can easily be transformed into ((a*c**d)/b)/x**d
, so the function we actually have to consider is of the form a/x**b
.
Now to the actual curve fitting with scipy:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
x = [0.723938224, 0.965250965, 1.206563707, 1.447876448, 1.689189189, 1.930501931, 2.171814672]
y = [2.758, 2.443, 2.142333333, 1.911, 1.817666667, 1.688333333, 1.616]
deffunc(x, a, b):
return a/(x**b)
#start values, not really necessary here but good to know the concept
p0 = [2, 0.5]
#the actual curve fitting, returns the parameters in popt and the covariance matrix in pcov
popt, pcov = curve_fit(func, np.asarray(x), np.asarray(y), p0)
#print out the parameters a, bprint(*popt)
#a=2.357411406488454, b=0.5027391574181408#plot the function to see, if the fit is any good#first the raw data
plt.scatter(x, y, marker="x", color="red", label="raw data")
#then the fitted curve
x_fit = np.linspace(0.9*min(x), 1.1*max(x), 1000)
y_fit = func(x_fit, *popt)
plt.plot(x_fit, y_fit, color="blue", label="fitted data")
plt.legend()
plt.show()
Looks good to me. And one shouldn't let Excel near any statistical data, if you asked me.
Post a Comment for "Use Of Curve_fit To Fit Data Of 2 Variables In A List"