Week 5 - Curve fitting
1) eg:- def func1 (t, a, b):
return a*t + b
The curve_fit function returns two items, which we can be stored in popt and pcov. The popt argument are the best-fit paramters for function inputs (a,b).
The pcov variable contains the covariance matrix, which indicates the uncertainties and correlations between parameters. This is mostly useful when the data has uncertainties.
covariance:- The mean value of the product of the deviations of two variates from their respective means.
2) A numpy array is a grid of values, all of the same type, and is indexed by a data structure consisting of multiple parts of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a data structure consisting of multiple parts of integers giving the size of the array along each dimension.
thus in the program the np.temperature create the array of values with rank-1 which helps the program to select the particular temperature and calculate the cp value for the cure.
3) In the program * is pointer which store the address of the variables in an array. *popt gives out the integer value of constants.
4)
"""
A python program to obtain the best curve fit for the available
thermodynamic data file
by Rupesh
"""
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# Curve fit function
def func1 (t, a, b):
return a*t + b
def func2 (t, a, b, c, d):
return a*pow(t,3) + b*pow(t,2) + c*t + d
#Reading thermodynamic data file
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]
# main Program
temperature,cp = read_file()
popt1,pcov1 = curve_fit (func1, temperature, cp)
popt2,pcov2 = curve_fit (func2, temperature, cp)
fit_cp1 = func1 (np.array (temperature), *popt1)
fit_cp2 = func2 (np.array (temperature), *popt2)
# plotting the actual and estimated curves
plt.figure()
plt.plot(temperature, cp , color = 'blue', lw = 3)
plt.plot(temperature, fit_cp1, color = 'red', lw = 3)
plt.legend(['Actual data', 'linear cure fit'])
plt.title(' Linear curve fit')
plt.xlabel('Temperature[k]')
plt.ylabel('cp')
plt.figure()
plt.plot(temperature, cp , color = 'blue', lw = 3)
plt.plot(temperature, fit_cp2, color = 'green', lw = 3)
plt.legend(['Actual data', 'cubical cure fit'])
plt.title(' Cubical curve fit')
plt.xlabel('Temperature[k]')
plt.ylabel('cp')
plt.show()
5) By observation it is noted that the increase in degree of polynomial gives us the prefect curve fit. Thus in the given problem cubic curves can be made as best fits.