import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#Curve fit functions
def linear_func(t,a,b):
return a*t+b
def quadratic_func(t,a,b,c):
return a*pow(t,2)+b*t+c
def cubic_func(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
def quartic_func(t,a,b,c,d,e):
return a*pow(t,4)+b*pow(t,3)+c*pow(t,2)+d*t+e
#Function to read data file
def read_file():
temp = []
cp = []
for line in open('data','r'):
value = line.split(',')
temp.append(float(value[0]))
cp.append(float(value[1]))
return[temp,cp]
#Curve fit for linear equation
temp,cp = read_file()
popt,pcov = curve_fit(linear_func,temp,cp)
fit_cp = linear_func(np.array(temp),*popt)
plt.figure(1)
plt.plot(temp,cp,color='blue')
plt.plot(temp,fit_cp,color='red')
plt.legend(['Actual data','Curve fit'])
plt.title('Linear curve fit')
plt.xlabel('Temprature in [k]')
plt.ylabel('Cp')
#Curve fit for quadratic equation
popt,pcov = curve_fit(quadratic_func,temp,cp)
fit_cp = quadratic_func(np.array(temp),*popt)
plt.figure(2)
plt.plot(temp,cp,color='blue')
plt.plot(temp,fit_cp,color='red')
plt.legend(['Actual data','Curve fit'])
plt.title('Quadratic curve fit')
plt.xlabel('Temprature in [k]')
plt.ylabel('Cp')
#Curve fit for cubic equation
popt,pcov = curve_fit(cubic_func,temp,cp)
fit_cp = cubic_func(np.array(temp),*popt)
plt.figure(3)
plt.plot(temp,cp,color='blue')
plt.plot(temp,fit_cp,color='red')
plt.legend(['Actual data','Curve fit'])
plt.title('Cubic curve fit')
plt.xlabel('Temprature in [k]')
plt.ylabel('Cp')
#Curve fit for quartic equation
popt,pcov = curve_fit(quartic_func,temp,cp)
fit_cp = quartic_func(np.array(temp),*popt)
plt.figure(4)
plt.plot(temp,cp,color='blue')
plt.plot(temp,fit_cp,color='red')
plt.legend(['Actual data','Curve fit'])
plt.title('Quartic curve fit')
plt.xlabel('Temprature in [k]')
plt.ylabel('Cp')
plt.show()