Example: biquadratic curve fitting python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def funcl(t, a, b):
return a*t +b
def funcq(t, a, b, c):
return a*pow(t,2) + b*t +c
def funcc(t, a, b, c,d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
def funcb(t, a, b, c, d, e):
return a*pow(t,4) + b*pow(t,3) + c*pow(t,2) + d*t + e
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(funcl,temperature,cp)
fit_cp = funcl(np.array(temperature), *popt)
popt, pcov = curve_fit(funcq,temperature,cp)
fit_cp2 = funcq(np.array(temperature), *popt)
popt, pcov = curve_fit(funcc,temperature,cp)
fit_cp3 = funcc(np.array(temperature), *popt)
popt, pcov = curve_fit(funcb,temperature,cp)
fit_cp4 = funcb(np.array(temperature), *popt)
plt.plot(temperature, cp,color="blue",linewidth=3)
plt.plot(temperature, fit_cp,color="red",linewidth=2)
plt.plot(temperature, fit_cp2,color="green",linewidth=2)
plt.plot(temperature, fit_cp3,color="yellow",linewidth=2)
plt.plot(temperature, fit_cp4,color="black",linewidth=2)
plt.legend(['Actual data','linear','quadratic','cubic','biquadratic'])
plt.xlabel('Temperature [K]')
plt.ylabel('Cp [j/kg]')
plt.title('Curve fitting')
plt.show()