Week 5 - Curve fitting
Curve fitting can be defined as the process of constructing a curve or mathematical function that has the best fit to a
series of data points, subject to constraints.
In this project, the curve for Specific heat as a function of Temperature will be plotted and the plot will be compared with
the actual plot.
The specific heats at different temperatures will be provided as inputs.
Initially, we will be writing a program for linear and cubic polynomial and check the results with the actual plot. Based on
the results obtained, we are going to figure out the best possible ways to have a perfect fit.
popt: It gives an array with the optimal values for the parameters so that the sum of the squared residuals of data is minimized
pcov: It is a 2d array with the estimated covariance of the parameters in popt. It can be used to calculate the the standard deviation
errors of popt.
np.array(temperature): This function stores the values of temperature in the form of array and passes it to the function numpy.
* in *popt: It stores the values of the constant parameters(a,b,c) in the array popt.
Program:
#curve fit for linear equation
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#curve fit function
def func_linear(t,a,b):
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_linear,temperature,cp)
fit_cp=func_linear(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp,color="red",linewidth=3)
plt.title('Specific Heat Vs Temperature')
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()
#curve fit for cubic equation
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#curve fit function
def func_cubic(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
temperature,cp=read_file()
popt,pcov=curve_fit(func_cubic,temperature,cp)
fit_cp=func_cubic(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature,fit_cp,color="red",linewidth=3)
plt.title('Specific Heat Vs Temperature')
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('cp')
plt.show()

