Curve Fitting in Python
Aim: To execute code to fit a linear and cubic polynomial for the Cp data using Python as the scripting language.
Introduction:
CODE:
#Program to perfrom curve fitting for a cubic polynomial
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit #curve_fit() function imported from scipy
#Reading the data file
def read_file():
temperature=[]
cp=[]
for line in open('data','r'): #opening the file and reading the data
values=line.split(',') #splitting lines using comma
temperature.append(float(values[0])) #adding data into the temp file
cp.append(float(values[1]))
return[temperature,cp]
#Curve fit function
#linear fit
def func(t,a,b):
return a*t+b
#main program
temperature,cp = read_file() #calling the function read_file and storing the values into temperature and cp
popt,pcov=curve_fit(func,temperature,cp) #popt= coefficeints and pcov= estimated covariance of popt
fit_cplinear=func(np.array(temperature),*popt) #passing temperature as numpy array
#Plotting
plt.figure(1)
plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cplinear,color='red',linewidth=3)
plt.legend(['Actual data','Linear Fit'])
plt.title('Temperature vs Specific Heat')
plt.xlabel('Temperature[K]')
plt.ylabel('Specific Heat')
plt.show()
#Reading the data file
#Cubic fit
def func (t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
temperature,cp = read_file()
popt,pocv=curve_fit(func,temperature,cp)
fit_cpcubic=func(np.array(temperature),*popt)
#Plotting
plt.figure(2)
plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cpcubic,color='red',linewidth=3)
plt.legend(['Actual data','Cubic Fit'])
plt.title('Temperature vs Specific Heat')
plt.xlabel('Temperature[K]')
plt.ylabel('Specific Heat')
plt.show()
#Comparison of linear and cubic curve fit
plt.figure(3)
plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cplinear,color='red',linewidth=3)
plt.plot(temperature,fit_cpcubic,color='yellow',linewidth=3)
plt.legend(['Actual Data','Linear Fit','Cubic Fit'])
plt.title('Temperature vs Specific Heat')
plt.xlabel('Temperature[K]')
plt.ylabel('Specific Heat')
plt.show()
OUTPUTS:
1. Linear fit Curve
2. Cubic Fit Curve
3. Comparison of actual data set, linear fit curve and cubic fit curve.
5. From the above codes, we see that when the order of the polynomial gets higher, then a better fit is obtained.
In order to make the curve fit perfect, we need to increase the order of the polynomial. The fit is perfect when R² value is equal to 1. This is obtained when the predicted curve and the actual data set curve meet at all the points.
CONCLUSION:
It is observed that by increasing the order of the polynomial the error between the curve fit and the original data set is reduced. Thus, we can conclude by saying that the result obtained from the linear curve fit is poor when compared to the cubic curve fit.