Challenge

Week 5 - Curve fitting

Curve fitting

AIM - To explain the parameters used to measure the fitness characteristics for curves.

OBJECTIVE -

  • Write code to fit a linear and cubic polynomial for the Cp data.
  • Plot the linear and cubic fit curves along with the raw data points.

RELATED THEORY :-

Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values, etc. It is highly effective in the mathematical modelling of some natural processes.

1.What does popt and pcov mean?

" popt " is an array that stores the values of the coefficients that are being passed in a given function .

" pcov " is an two dimensional array that stores the values of the estimated covarience of popt i.e the coefficients .

2.What does np.array(temperature) do?

The above command is used for passing the vales of temperature as a numpy array .

3.What does the * in *popt mean?

" * " in *popt helps us to refer to the coefficients in a given equation.

Python Code

Linear

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


#Curve_fit function
def func(t,a,b,c):
	return a*t+b

#Reading 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]


temperature,cp = read_file()
popt,pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)

#Plotting the curves
plt.plot(temperature,cp,color="blue",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()

Cubic

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit


#Curve_fit function
def func(t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2) + c*t + d

#Reading 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]


temperature,cp = read_file()
popt,pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array(temperature),*popt)

#Plotting the curves
plt.plot(temperature,cp,color="blue",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()

Results

For linear

For cubic

Explanation of Results

Importing math for the mathematical calculation, importing numpy to create an array of temperature, importing matplotlib.pyplot for plotting the graph of temperature and specific heat , and from scipy moudule importing curve fit to perform the curve fit.

Linear equation and cubic equation are defined in the function so that they can be called later in the main program while performing the curve fitting .

For the thermodynamic data available with us we use “open” command to open the file following with the letter “r” to get in the read mode. As there is huge amount of data in our file , we use for loop to read every line and split the data with the comma “ , “ in the lines of the data using split function.

Temperature and specific heat are stored in separate arrays , using numpy module

Curve fit is done which returns two arrays “popt” and “pcov” , popt is the Optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized .

Where as the “pcov” means The estimated covariance of popt. The diagonals provide the variance of the parameter estimate .

In passing the command popt in curve fit we have used it as the *popt , that is because the * is the pointer operator and points out all the elemnts in that array .

The predicted cp is calculated as the fit_cp for the linear and the cubic function .

The graph is plotted using the predicted cp of the polynomals, and compared with the original data set.

Conclusion

By using the higher order polynomials we minimize the error , as we can see in the above graph that cubic fit fits the curve best than the linear fit.

As we can see from the above programme splitting the entire data into some would fits the curve better rather than using one higher order polynomial for the entire data.

And for the lesser values of temperature we can observe that lower order polynomials fits , and as the data size and the values increases the order of polynomial should increase to get the best fit.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.