Week 5 - Curve fitting
Important Information
- The popt and pcov are the outputs of called curve_fit function. popt contains coefficients, whereas the pcov represents the calculated covariance of popt.
- The np.array(temperature) function passes temperature as array.
- The * in *popt passes the multiple arguments in the function call.
- Codes
- Linear curve fit
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# curve fit function
def func(t, a, b):
return a*t+b
def read_file ():
temp=[]
cp=[]
for line in open ('data', 'r'):
values=line.split(',')
temp.append(float (values[0]))
cp.append(float(values[1]))
return (temp, cp)
# main program
temperature, cp=read_file()
popt, pcov=curve_fit(func, temperature, cp)
fit_cp=func(np.array(temperature), *popt)
plt.plot(temperature, cp,, linewidth=3)
plt.plot(temperature, fit_cp,, linewidth=3)
plt.legend(['Acutal_Data', 'curve_fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Specific Heat')
plt.show()
Related Plot
- Cubic polynomial curve fit
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# curve fit function
def func(t, a, b, c, d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
def read_file ():
temp=[]
cp=[]
for line in open ('data', 'r'):
values=line.split(',')
temp.append(float (values[0]))
cp.append(float(values[1]))
return (temp, cp)
# main program
temperature, cp=read_file()
popt, pcov=curve_fit(func, temperature, cp)
fit_cp=func(np.array(temperature), *popt)
plt.plot(temperature, cp,, linewidth=3)
plt.plot(temperature, fit_cp,, linewidth=3)
plt.legend(['Acutal_Data', 'curve_fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Specific Heat')
plt.show()
Related Plot
Conclusion
For a linear equation, the curve obtained using curve_fit function is more spread (modelled data points are more spread from actual data points). In the linear curve fit function, the error is more in comparison to the polynomial curve fit function. Curve obtained with the polynomial equation is overlapping the actual curve, hence it can be considered as the good fit.
5. In order to make the curve fit perfect, the order of the equation must be increased.