Week 5 - Curve fitting
- What does popt and pcov mean?
Ans:
Popt-Popt is an array of optimal values for the parameters which minimize the sum of squares of residuals.
Pcov- pcov is a 2d array that contains the estimated covariance of popt. The diagonals provide the variance of the parameter estimate.
- What does np.array(temperature) do?
Ans:
np.array: np.array converts the python list of temperature to a numpy array since operations like pow are allowed on numpy arrays and not python lists.
- What does the * in *popt mean?
Ans:
*-reference to popt/the values stored in the array popt.
- Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
Ans:
Python programming codes for linear polynomial are given below:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#curve fit function
def func(t,a,b,c,d,e):
return a*t+b
# reading thermodynamic data file
def read_file():
temperature=[]
cp=[]
for line in open ('data', 'r'):
values =line.split(',')
temperature.append(float(values[0]))
cp.append(float(values[1]))
return [temperature,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,color="green",linewidth=3.5)
plt.plot(temperature,fit_cp,color="blue",linewidth=3.5)
plt.legend(['actual data','curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('Cp')
plt.show()
Output:

Python programming codes for cubic polynomial:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# curve fitting function
def func(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
#reading Thermodynamic data file
def read_file():
temperature=[]
cp=[]
for line in open ('data','r'):
values =line.split(',')
temperature.append(float(values[0]))
cp.append(float(values[1]))
return [temperature,cp]
# main program for plotting
temperature, cp=read_file()
popt,pcov=curve_fit(func,temperature,cp)
fit_cp=func(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3.5)
plt.plot(temperature,fit_cp,color="red",linewidth=3.5)
plt.legend(['actul data','curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('cp')
plt.show()
Output:

Result Explanation :
The results are good because the cubic fit is better to curve fit than the linear one as we can see from the output plots.
- What needs to be done in order to make the curve fit perfectly?
Ans:
By increasing the degree of the curve we can make the best curve fit.
If we further increase the degree of the curve to 4 then the curve will be more accurate than the cubic polynomial.
Further increasing the degree of the polynomial will increase the calculating complexity and time required, hence 4th order polynomial can be taken as a sufficient curve fit.