Curve fitting in Python
Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to an orginal dataset. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values or measure the errors between an orginal pre-defined datasets and predicted data. It is highly effective in the mathematical modelling of some natural processes such as forecasting the population of a country, or a companys marketting sales over a period of time. This pedicted data may not be the exact data but can be used to interpolate values and predicting the growth of the curv(data) in near future.
Curve fit module calculates coefficients(accordinig to the order of polynomial) and output as popt. popt contains coefficients a,b,c,d, etc. pcov estimates covarience of popt.
np.array(temperature) is used to put all the values of temperature one by one in array using numpy module
* in *popt denotes the coefficients of polynomial, that it contains
Code:
In this program, the data is splitted into three ranges, 1:499, 500:1599, 1600:3200. For the ranges, linear, cubic & linear curve fittings are done, respectively
Piecewise function
'''
Objective : Curve fitting in Python
Coded by : S.Sai Srinath
'''
# Importing modules
import math
import numpy as np
import scipy.optimize as sp
import matplotlib.pyplot as plt
# Function to read and store the given data
def read(file):
temp=[]
Cp=[]
for l in open(file,'r'):
val=l.split(',')
temp.append(float(val[0]))
Cp.append(float(val[1]))
return [temp,Cp]
# Curve fitting functions
def f1(T,a,b,c,d):
y=a*pow(T,3)+b*pow(T,2)+c*T+d
return y
def f2(T,a,b):
y=a*T+b
return y
# Reading the given data file
T,Cp=read('data')
# Initializing
T1=[]
T2=[]
T3=[]
Cp1=[]
Cp2=[]
Cp3=[]
i=0
# Sorting the values
for t in T:
c=Cp[i]
if t<500:
T1.append(t)
Cp1.append(c)
elif t>500 and t<1600:
T2.append(t)
Cp2.append(c)
elif t>1600:
T3.append(t)
Cp3.append(c)
i=i+1
# Curve fitting
coeff1,covar1=sp.curve_fit(f2,T1,Cp1)
coeff2,covar2=sp.curve_fit(f1,T2,Cp2)
coeff3,covar3=sp.curve_fit(f2,T3,Cp3)
# Calculating the function values
y1=f2(np.array(T1),*coeff1)
y2=f1(np.array(T2),*coeff2)
y3=f2(np.array(T3),*coeff3)
# Plotting the actual and fitted functions
plt.plot(T,Cp,label='Actual')
plt.plot(T1,y1,label='linear Fit')
plt.plot(T2,y2,label='cubic Fit')
plt.plot(T3,y3,label='linear Fit')
plt.title('Cp Vs Temperature')
plt.xlabel('Temperature(K)')
plt.ylabel('Cp')
plt.legend()
plt.show()
# Displaying the plot
Result:
The cubic fit is more comparable to data as compared to linear fits. It is clear that as the order of polynomial is increased, the curve fit becomes good.
cubic curve fitting:
'''
Objective : Curve fitting in Python
Coded by : S.Sai Srinath
'''
# Importing modules
import math
import numpy as np
import scipy.optimize as sp
import matplotlib.pyplot as plt
# Function to read and store the given data
def read(file):
temp=[]
Cp=[]
for l in open(file,'r'):
val=l.split(',')
temp.append(float(val[0]))
Cp.append(float(val[1]))
return [temp,Cp]
# Curve fitting function
def f(T,a,b,c,d):
y=a*pow(T,3)+b*pow(T,2)+c*T+d
return y
# Reading the given data file
T,Cp=read('data')
# Curve fitting
coeff,covar=sp.curve_fit(f,T,Cp)
# Calculating the function values
Cp_fit=f(np.array(T),*coeff)
# Plotting the actual and fitted functions
plt.plot(T,Cp,label='Actual')
plt.plot(T,Cp_fit,label='Fit')
plt.title('Cp Vs Temperature')
plt.xlabel('Temperature(K)')
plt.ylabel('Cp')
plt.legend()
plt.show()
# Displaying the plot
Result:
Bi-quadratic curve fitting:
'''
Objective : Curve fitting in Python
Coded by : S.Sai Srinath
'''
# Importing modules
import math
import numpy as np
import scipy.optimize as sp
import matplotlib.pyplot as plt
# Function to read and store the given data
def read(file):
temp=[]
Cp=[]
for l in open(file,'r'):
val=l.split(',')
temp.append(float(val[0]))
Cp.append(float(val[1]))
return [temp,Cp]
# Curve fitting function
def f(T,a,b,c,d,e):
y=a*pow(T,4)+b*pow(T,3)+c*pow(T,2)+d*T+e
return y
# Reading the given data file
T,Cp=read('data')
# Curve fitting
coeff,covar=sp.curve_fit(f,T,Cp)
# Calculating the function values
Cp_fit=f(np.array(T),*coeff)
# Plotting the actual and fitted functions
plt.plot(T,Cp,label='Actual')
plt.plot(T,Cp_fit,label='Fit')
plt.title('Cp Vs Temperature')
plt.xlabel('Temperature(K)')
plt.ylabel('Cp')
plt.legend()
plt.show()
# Displaying the plot
Result:
How to improve goodness of cubic fit?
- By increasing the order of polynomial in curve fitting toolbox
- By splitting the data values into many ranges using split-wise polynomial
- By adding points with distinct X values