Project

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:

Curve fitting is the process of building a curve, or a mathematical function, which is best suited to a series of data points, possibly constraints. By curve fitting, we can mathematically construct the functional relationship between the observed data set and the parameter values etc.
Curve fitting may entail either interpolation, where accurate fit to the data is needed or smoothing, where a "smooth" function is developed that suits the data approximately.
It is highly effective in the mathematical modelling of some natural processes.
Some important terms used in the program:
1. popt and pcov -
popt is an array that stores the values of the coefficients that are being passed in a given function. This array basically, gets the optimised parameters for the filled functions.
2. pcov - It is a two-dimensional array that stores the values of the estimated covariance of popt (i.e; Coefficients )
3. np.array - This command is used for passing the values of temperature as a bumpy array; since operations like pow are allowed on bumpy arrays and not on python lists.
4. *in*popt - This helps us to unpack the array and supply the arguments for remaining parameters.

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.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.