Curve Fitting Given Data using Python
AIM: Python code to Curve fit a linear and cubic polynomial for the given Cp data.
DATA File Link: Data For Curve Fitting
CODE:
"""
Linear and Cubic Polynomial curve fit for the cp data
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Linear polynomial curve fit
def fun1(t1, a1, b1):
return a1*t1 + b1
# Cubic polynomial curve fit
def fun2(t2, a2, b2, c2, d2):
return a2*pow(t2,3) + b2*pow(t2,2) + c2*t2 + d2
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]
temperature, cp=read_file()
popt, pcov=curve_fit(fun1,temperature,cp)
fit_cp1=fun1(np.array(temperature), *popt)
popt, pcov=curve_fit(fun2,temperature,cp)
fit_cp2=fun2(np.array(temperature), *popt)
plt.figure(1)
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')
plt.ylabel('Cp')
plt.figure(2)
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')
plt.ylabel('Cp')
plt.show()
OUTPUT:
1. LINEAR CURVE FIT
2. CUBIC CURVE FIT
EXPLANATION:
Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values, etc. It is highly effective in the mathematical modeling of some natural processes.
In this program we first import the numpy, matplotlib and scipy module.
Then we define two function, one for linear polynomial and another for cubic polynomial as shown in the coding.
Then we get the value of cp with respect to temperature. By using line.split(',') command we split the temperture and cp value fo oxygen and append to temperature and cp array as shown in coding.
Then we calculate fit curve by using the below command,
popt, pcov=curve_fit(fun1,temperature,cp)
fit_cp1=fun1(np.array(temperature), *popt)
Finally plot the original curve and calculated curve fit of cp data with respect to temperature.
From this analysis, increasing the order of polynomials gives better curve fit. So if we use fourth order polynomial we get a better curve fit.