Week 5 - Curve fitting
1. popt and pcov
Popt = An array that holds the value of the coefficients of variables in a function. pcov = An array that stores the covariance (cov) of the coefficients of the variables in the given function. Covariance is the variance between the two variables required of tge curve fit.
2. np.array(temperature)
np.array() is a function from the numpy library which creates the array with the required arguments. Here, an array consisting of temperature values is created.
3.* in *popt
The '*' in '*ppot' refers to the coefficients of variables stored in the 2-D popt array
4. Curve fit program
"""
CURVE FIT FOR LINEAR FUNCTION
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def linfunc(t,a,b): #To return linear curve fit data
return a*t+b
def cubicfunc(t,a,b,c,d): #To return cubic linear curve fit data
return a*pow(t,3)+b*pow(t,2)+c*t+d
return
def read_file(): #Rea temp and cp values from the document
temp=[]
cp=[]
for line in open ('data','r'):
values=line.split(',')
temp.append(float(values[0]))
cp.append(float(values[1]))
return[temp,cp]
temp,cp=read_file()
popt,pcov=curve_fit(linfunc,temp,cp) #To list coefficient and covarience of coefficients of temp and cp
linfit_cp=linfunc(np.array(temp),*popt)
popt,pcov=curve_fit(cubicfunc,temp,cp)
cubicfit_cp=cubicfunc(np.array(temp),*popt)
#PLOTS
plt.plot(temp,cp,color="red",linewidth=3)
plt.title('Actual Data')
plt.xlabel('temperature[K]')
plt.ylabel('cp')
plt.show()
plt.plot(temp,linfit_cp,color="blue",linewidth=3)
plt.title('Linear curve fit Data')
plt.xlabel('temperature[K]')
plt.ylabel('cp')
plt.show()
plt.plot(temp,cubicfit_cp,color="green",linewidth=3)
plt.title('Cubic curve fit Data')
plt.xlabel('temperature[K]')
plt.ylabel('cp')
plt.show()
plt.plot(temp,cp,color="red",linewidth=3)
plt.plot(temp,linfit_cp,color="blue",linewidth=3)
plt.plot(temp,cubicfit_cp,color="green",linewidth=3)
plt.legend(['actual data','linear curve fit data','cubic curve fit data'])
plt.xlabel('temperature[K]')
plt.ylabel('cp')
plt.show()
PLOTS
5. To make the curve fit perfect
The best curve fit can be selected by comparing the truncation errors of the various models and selecting the one with the least error.