biquadratic curve fitting python code example

Example: biquadratic curve fitting python

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit

#curve fit functions

#linear function
def funcl(t, a, b):
	return a*t +b

#quadratic function
def funcq(t, a, b, c):
	return a*pow(t,2) + b*t +c

#cubic function
def funcc(t, a, b, c,d):
	return a*pow(t,3) + b*pow(t,2) + c*t + d

#biquadratic function
def funcb(t, a, b, c, d, e):
	return a*pow(t,4) + b*pow(t,3) + c*pow(t,2) + d*t + e

#reading the data file
def read_file():
	temperature = []
	cp = []
	for line in open('data','r'):
		#Splitting the data using the comma operator 
		values = line.split(',')

#sending the first and second values to temperature and Cp respectively using append
		temperature.append(float(values[0]))
		cp.append(float(values[1]))

	return [temperature,cp]

#main program

#calling the read function
temperature,cp = read_file()

#Using inbuilt function for linear fit
popt, pcov = curve_fit(funcl,temperature,cp)
fit_cp = funcl(np.array(temperature), *popt)

#Using inbuilt function for quadratic fit
popt, pcov = curve_fit(funcq,temperature,cp)
fit_cp2 = funcq(np.array(temperature), *popt)

#Using inbuilt function for cubic fit
popt, pcov = curve_fit(funcc,temperature,cp)
fit_cp3 = funcc(np.array(temperature), *popt)

#Using inbuilt function for biquadratic fit
popt, pcov = curve_fit(funcb,temperature,cp)
fit_cp4 = funcb(np.array(temperature), *popt)


#plotting the respective curve fits 
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()

Tags:

Misc Example