Curve fit using python
AIM:
To write a code for linear and cubic polynomial to get the accurate curve fit.
ANSWERS FOR THE IMPORTANT QUESTIONS:
1. What does popt and pcov mean?
- popt-It is an array of values for the given declared parameters to minimize the sum of the squares of the values.
2. What does np.array(temperature) do?
It stores the values of temperature as array and passes to the numpy function.
3. What does the * in *popt mean?
It is used to call the arguments of calling the co-efficients individually for the function.
PROGRAM FOR PERFORMING LINEAR POLYNOMIAL FOR CURVE_FIT:
#PROGRAM FOR THE LINEAR POLYNOMIAL EQUATION FOR FINDING CURVE FIT:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#FUNCTION FOR THE CURVE FIT:
def func(t, a, b, c):
return a*t + b*t + c
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,linewidth=2)
plt.plot(temperature,fit_cp,linewidth=2)
plt.legend([\'Actual Data\', \'Curve Fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'cp\')
plt.grid()
plt.show()
OUTPUT:
PROGRAM FOR PERFORMING CUBIC POLYNOMIAL FOR CURVE_FIT:
#PROGRAM FOR THE CUBIC POLYNOMIAL EQUATION FOR FINDING CURVE FIT:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#FUNCTION FOR THE CURVE FIT:
def func(t,a,b,c,d):
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,linewidth=2)
plt.plot(temperature,fit_cp,linewidth=2)
plt.legend([\'Actual Data\', \'Curve fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'cp\')
plt.grid()
plt.savefig(\'cubic_fit\')
plt.show()
OUTPUT:
EXPLANATION OF BOTH PLOTS:
- In first plot there is huge difference between the values of actual and curve fit data.
- But,the second one has more close fit than the first one.
- Higher Degree Polynomial makes the sense.
5. What needs to be done in order to make the curve fit perfect?
In order to get the accurate curve fit ,high degree polynomial is used.By using high order of polynomial the accuracy is reached for maximum level.