The curve fitting cp vs temperature data file
# Curve Fitting
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Curve fit function
def linear(t,a,b):
return a*t + b
def quadratic(t,a,b,c):
return a*pow(t,2) + b*t + c
def cubic(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(linear,temperature,cp)
fit_cp = linear(np.array(temperature),*popt)
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature,fit_cp,color=\"red\",linewidth=3)
plt.legend([\'Actual data\',\'Curve Fit\'])
plt.xlabel(\'Temperature[K]\')
plt.ylabel(\'Cp\')
plt.show()
popt,pcov = curve_fit(quadratic,temperature,cp)
fit_cp = quadratic(np.array(temperature),*popt)
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature,fit_cp,color=\"red\",linewidth=3)
plt.legend([\'Actual data\',\'Curve Fit\'])
plt.xlabel(\'Temperature[K]\')
plt.ylabel(\'Cp\')
plt.show()
popt,pcov = curve_fit(cubic,temperature,cp)
fit_cp = cubic(np.array(temperature),*popt)
plt.plot(temperature,cp,color=\"blue\",linewidth=3)
plt.plot(temperature,fit_cp,color=\"red\",linewidth=3)
plt.legend([\'Actual data\',\'Curve Fit\'])
plt.xlabel(\'Temperature[K]\')
plt.ylabel(\'Cp\')
plt.show()
% Linear fit
clear all
close all
clc
% Data
cp_data = load(\'data\');
temperature = cp_data(:,1);
cp = cp_data(:,2);
plot(temperature,cp,\'linewidth\',3);
xlabel(\'Temperature[K]\');
ylabel(\'Specific Heat[kJ/kmol-K]\');
hold on
% Curve Fitting
co_efficients = polyfit(temperature,cp,1);
cp_fit = polyval(co_efficients,temperature);
plot(temperature,cp_fit,\'linewidth\',3);
legend(\'Original data\',\'Curve-fit\');
Linear_fit.m
Displaying Linear_fit.m.
% cubic fit
clear all
close all
clc
% Data
cp_data = load(\'data\');
temperature = cp_data(:,1);
cp = cp_data(:,2);
plot(temperature,cp,\'linewidth\',3);
xlabel(\'Temperature[K]\');
ylabel(\'Specific Heat[kJ/kmol-K]\');
hold on
% Curve Fitting
co_efficients = polyfit(temperature,cp,3);
cp_fit = polyval(co_efficients,temperature);
plot(temperature,cp_fit,\'linewidth\',3);
legend(\'Original data\',\'Curve-fit\');
In order to get a perfect fit curve, we need to try fitting higher order polynomials and depending on the fit we get, we may need to break the temperature range and try different polynomials for each range which best fits that range