Week 5 - Curve fitting
Curve fitting
1. What does popt and pcov mean?
popt-It is an array.This will be our coefficients in the program.It represents the unknowns in the function defined in the program so later it will be the output as it curve fit function calculates it.Or in other words optimal values for the parameters so that the sum of the squared error is minimized.
pcov-The estimated covariance of popt. The diagonals provide the variance of the parameter estimate.
2. What does np.array(temperature) do?
np.array(temperature) stores the values of temperature in the form of array and passes it to numpy function.
3. What does the * in *popt mean?
It stores the values of unknown variables in popt array.
4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
"""
Program for curve fitting of linear polynomial from ABHISHEK M B
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(t,a,b,c,d,e):
return a*t + b
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(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
plt.plot(temperature,cp,color = "green",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()
"""
Program for curve fitting of cubic polynomial from ABHISHEK M B
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(t,a,b,c,d,e):
return a*pow(t,3) + b*pow(t,2) + c*t + d
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(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)
plt.plot(temperature,cp,color = "green",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()
Result of Linear Polynomial:

Result of Cubic Polynomial:

From the above two plots we can see that the cubic polynomial's curve fit looks like a good curve fit than linearpolynomial's curve fit.
5. What needs to be done in order to make the curve fit perfect?
By increasing degree of curve the curve fit will be more accurate.
By using splitwise polynomial also curvefit will be accurate.