Week 5 - Curve fitting
1. The popt are best fit argument for the variables.
pcov variable contains the covariance matrix which indicates uncertainities and correlations between parameters. This is mostly useful when data has uncertainities.
2. np.array() is used so that array operations can be used on the list of temperatures. It is a part of the numpy module.
3. * represents args and ** represent kwargs.
* unpacks a list or tuple into position arguments
** unpacks a dictionary into keyword arguments
4.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# linear curve fit function
def linear_func(t,a,b):
return a * t + b
#cubic curve fit function
def cubic_func(t,c,d,e,f):
return c * pow(t,3) + d * pow(t,2) + e * t + f
# 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(linear_func, temperature, cp)
fit_cp = func(np.array(temperature), *popt)
plt.plot(temperature, cp, color = 'blue' , linewidth = 3)
plt.plot(temperature, fit_cp, color = 'red' , linewidth = 3)
plt.legend(['Actual data', 'curve fit'])
plt.xlabel('Temperature [K]')
plt.ylabel('Cp')
plt.show()
5. To make the curve more and more perfect one should increase the degree of the tracing curve.