biquadratic curve fitting python

Solutions on MaxInterview for biquadratic curve fitting python by the best coders in the world

showing results for - "biquadratic curve fitting python"
Matteo
30 Apr 2018
1import numpy as np 
2import matplotlib.pyplot as plt 
3from scipy.optimize import curve_fit
4
5#curve fit functions
6
7#linear function
8def funcl(t, a, b):
9	return a*t +b
10
11#quadratic function
12def funcq(t, a, b, c):
13	return a*pow(t,2) + b*t +c
14
15#cubic function
16def funcc(t, a, b, c,d):
17	return a*pow(t,3) + b*pow(t,2) + c*t + d
18
19#biquadratic function
20def funcb(t, a, b, c, d, e):
21	return a*pow(t,4) + b*pow(t,3) + c*pow(t,2) + d*t + e
22
23#reading the data file
24def read_file():
25	temperature = []
26	cp = []
27	for line in open('data','r'):
28		#Splitting the data using the comma operator 
29		values = line.split(',')
30
31#sending the first and second values to temperature and Cp respectively using append
32		temperature.append(float(values[0]))
33		cp.append(float(values[1]))
34
35	return [temperature,cp]
36
37#main program
38
39#calling the read function
40temperature,cp = read_file()
41
42#Using inbuilt function for linear fit
43popt, pcov = curve_fit(funcl,temperature,cp)
44fit_cp = funcl(np.array(temperature), *popt)
45
46#Using inbuilt function for quadratic fit
47popt, pcov = curve_fit(funcq,temperature,cp)
48fit_cp2 = funcq(np.array(temperature), *popt)
49
50#Using inbuilt function for cubic fit
51popt, pcov = curve_fit(funcc,temperature,cp)
52fit_cp3 = funcc(np.array(temperature), *popt)
53
54#Using inbuilt function for biquadratic fit
55popt, pcov = curve_fit(funcb,temperature,cp)
56fit_cp4 = funcb(np.array(temperature), *popt)
57
58
59#plotting the respective curve fits 
60plt.plot(temperature, cp,color="blue",linewidth=3)
61plt.plot(temperature, fit_cp,color="red",linewidth=2)
62plt.plot(temperature, fit_cp2,color="green",linewidth=2)
63plt.plot(temperature, fit_cp3,color="yellow",linewidth=2)
64plt.plot(temperature, fit_cp4,color="black",linewidth=2)
65plt.legend(['Actual data','linear','quadratic','cubic','biquadratic'])
66plt.xlabel('Temperature [K]')
67plt.ylabel('Cp [j/kg]')
68plt.title('Curve fitting')
69plt.show()