Week 5 - Curve fitting
1. What does popt and pcov mean? (Watch the video to get some context)
popt is the output of the coefficient values in a polynomial equation. eg In a 3rd order polynomial, at3+bt2+ct+d = 0 , a,b,c and d are the coefficients.
pcov is the 2d array which contains the estimated covariance of popt.
2. What does np.array(temperature) do?
converts the temperature single values of each line into numpy array so that multiple numpy operations can be performed.
3. What does the * in *popt mean?
The '*' refers the popt values (coefficient values) and assigns it to the polynomial equation.
4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#curve fit linear
def func_linear(t,a,b):
return a*t + b
def readfile():
T= []
cp = []
for line in open('data','r'):
values = line.split(',')
T.append(float(values[0]))
cp.append(float(values[1]))
return[T,cp]
T,cp = readfile()
popt,pcov=curve_fit(func_linear,T,cp)
fitcp=func_linear(np.array(T),*popt)
plt.plot(T,cp,color = "blue")
plt.plot(T,fitcp,color = "red")
plt.title('Specific Heat vs Temperature')
plt.legend(['Actual Data','Curve Fit data'])
plt.xlabel('Temperature[k]')
plt.ylabel('cp')
plt.show()
#curve fit cubic
def func_cubic(t,a,b,c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
def readfile():
T1= []
cp1 = []
for line in open('data','r'):
values = line.split(',')
T1.append(float(values[0]))
cp1.append(float(values[1]))
return[T1,cp1]
T1,cp1 = readfile()
popt1,pcov1=curve_fit(func_cubic,T1,cp1)
fitcp1=func_cubic(np.array(T1),*popt1)
plt.plot(T1,cp1,color = "blue")
plt.plot(T1,fitcp1,color = "red")
plt.title('Specific Heat vs Temperature')
plt.legend(['Actual Data','Curve Fit data'])
plt.xlabel('Temperature[k]')
plt.ylabel('cp')
plt.show()
RESULTS:
Linear Fit

Cubic Fit

5. What needs to be done in order to make the curve fit perfect?
1. Increasing the order of the polynomial function will fit the curve perfectly
2. Using the split wise function so that the curve follows the smooth path.