Curve fitting using python
AIM
To write code in python for curve fitting
THEORY
Curve fitting is the process of constructing a curve or mathematical function, that has the best fit to a series of data points, possibly subject to constraints. it basically examines the relationship between one or more independent variables and a dependent variable, with the goal of defining a "best fit".
Types of curve fitting:
1. Linear curve fitting is when the data is fit to a straight line. Although there might be some curve to the data available, a straight line provides a reasonable enough fit to make predictions.
2. Polynomial curve fitting is when the data is fit to the graph of a polynomial function.
PROCEDURE
1. Necessary modules imported are numpy,matplotlib and scipy
2. The curve fit function is defined it can be linear or polynomial depending on the data
3. The thermodynamic data file is read using a function
- Create two arrays to read and store temperature and cp form the data file
- Split each data in the file by a comma using split function and store values of temperature and cp to the corresponding array using the append function.
4. The output obtained by curve_fit function is stored in the variables popt and pocv. curve_fit function takes the polynomial that should be fitted.
5. The values are plotted using the plot function.
PYTHON CODE
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Curve fit function
#Linear function
def func1(t,a,b):
return a*t+b
#Cubic function
def func2(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(func1,temperature,cp)
fit_cp1=func1(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature, fit_cp1,color="red",linewidth=3)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('temperature[K]')
plt.ylabel('Cp')
plt.title('Linear Curve Fitting')
plt.show()
popt,pcov=curve_fit(func2,temperature,cp)
fit_cp2=func2(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature, fit_cp2,color="red",linewidth=3)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('temperature[K]')
plt.ylabel('Cp')
plt.title('Cubic Curve Fitting')
plt.show()
RESULTS
The code was written to do linear as well as cubic curve fitting. The cubic curve fit is more accurate compared to the linear curve fit.
QUESTIONS
1.What does popt and pcov mean?
Ans: popt is a one dimensional array of the best estimates for the parameter values, each entry matches the order in the function definition, it contains the coefficients of the curve to be fitted. pcov is the covariance matrix showing the uncertainty and interdependence of each parameter in popt. Covariance indicates that how much two random variables vary together. It is similar to variance but variance tells how a single variable varies. Covariance tells how two variables vary together.
2. What does np.array(temperature) do?
Ans: np stands for numpy module is a python extension module. It provides fast and efficient operations on arrays of homogeneous data
3. What does the * in *popt mean?
Ans: * calls by value ie it returns the value of the coefficients of the curve equation
4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
Ans: The code to fit linear and cubic polynomial are given below
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Curve fit function
#Linear function
def func1(t,a,b):
return a*t+b
#Cubic function
def func2(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(func1,temperature,cp)
fit_cp1=func1(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature, fit_cp1,color="red",linewidth=3)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('temperature[K]')
plt.ylabel('Cp')
plt.title('Linear Curve Fitting')
plt.show()
popt,pcov=curve_fit(func2,temperature,cp)
fit_cp2=func2(np.array(temperature),*popt)
plt.plot(temperature,cp,color="blue",linewidth=3)
plt.plot(temperature, fit_cp2,color="red",linewidth=3)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('temperature[K]')
plt.ylabel('Cp')
plt.title('Cubic Curve Fitting')
plt.show()
The linear and cubic curve fitting can be compared by the result given below
The cubic curve fitting gives a better fit compared to the linear curve fitting. Hence the cubic curve fitting is good compared to the linear one.
5. What needs to be done in order to make the curve fit perfect?
Ans: While comparing linear and cubic curve fitting graphs we understood that, To make the curve fit perfect the order of the polynomial should be increased. As the order increases the error produced will be less.