Week 5 - Curve fitting
1. What does popt and pcov mean?
Ans: POPT is an array of optimal values for the parameters defined in the function to minimize the sum of the square of residual for given data is minimum in the least square method.
2. What does np. array(temperature) do?
Ans: A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. This command allows python to access individual elements in the list of temperatures with the help of numpy command.
3. What does the *in *popt means?
This command stores the value of the constant parameter(a,b,c) in the array popt.
4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.
Ans
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def linear(t,a,b):
return b*t +a
def cubic(t,a,b,c,d):
return d*pow(t,3) + c*pow(t,2) + b*t + a
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(linear,temperature,cp)
fit_cp_1 = linear(np.array(temperature),*popt)
plt.figure(1)
plt.plot(temperature,cp,color = "black",linewidth = 3)
plt.plot(temperature,fit_cp_1, color = "red", linewidth = 3)
plt.legend(['Actual data','curve fit'])
plt.xlabel('temperature')
plt.ylabel('cp')
plt.show()
temperature,cp = read_file()
popt,pcov = curve_fit(cubic,temperature,cp)
fit_cp_2 = cubic(np.array(temperature),*popt)
plt.figure(2)
plt.plot(temperature,cp,color = "black",linewidth = 3)
plt.plot(temperature,fit_cp_2, color = "red", linewidth = 3)
plt.legend(['Actual data','curve fit'])
plt.xlabel('temperature')
plt.ylabel('cp')
plt.show()
linear result

cubic result

The result is good for the cubic. therefore we can conclude it that as the degree of the polynomial is increases the goodness of curve fit is obtained.
5. What needs to be done in order to make the curve fit perfect?
Ans: In order to make a perfect fit, we must consider error estimates as well. The perfect fit means, the curve should fit the original curve without showing any errors (such as centering and scaling errors) in that particular degree of the polynomial. A perfect fit can always be the best fit but the best fit can not be a perfect fit. In the cubic polynomial we reduced error and we get the best fit but for a perfect fit the polynomial degree should increases.