Project

curve fit using python

Curve fitting is the process of constructing a curve, or mathematical function, that has the best fit to a series of data points, possibly subject to constraints. Curve fitting can involve either interpolation, where an exact fit to the data is required, or smoothing, in which a \"smooth\" function is constructed that approximately fits the data. A related topic is regression analsys which focuses more on questions of statistical inference such as how much uncertainty is present in a curve that is fit to data observed with random errors. Fitted curves can be used as an aid for data visualization, to infer values of a function where no data are available, and to summarize the relationships among two or more variables. Extrapolation refers to the use of a fitted curve beyond the range of the observed data, and is subject to a degree of uncertainity since it may reflect the method used to construct the curve as much as it reflects the observed data.

In python we can use scipy module to find the best curve fit for the given set of data.

scipy.optimize is imported as curve_fit to calculate the best curve fit.

the syntax of the function is popt,pcov=curve_fit(f, xdata, ydata).

popt gives the coefficient of the equation taken such that sum of the squared residuals of f(xdata, *popt) - ydata is minimized.

pcov gives the estimated covariance of popt. The diagonals provide the variance of the parameter estimate i.e standard deviation.

* in *popt denotes coefficients of polynomial or simply it is a pointer which points the coefficients of the polynomial.

np.array(temperature) is used to put all the values of temperature in an array using numpy module.

EXPLANATION OF THE PROGRAM:

Two functions are defined in the program, one for using polynomial and other to read file which has data for which curve fit must be done.

First column in the file are the values of the temperature and second column are the values of the values of the specific heat. These values are stored in arrays temperature and cp, by reading the file by opening it with open command and setting the function open to read the file and using line.split command values are taken which are seperated by \',\'. These values are then stored in temperature and cp respectively.

In the first function defined we can take either linear, quadratic, cubic, or polynomial of any degree and then use these polynomial for curve fit.

In this program linear, quadratic, cubic, polynomial of degree 4 and ploynomial of degree 9 are used to get the best curve fit.

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

#linear curve
def function(t,a,b):
	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(function,temperature,cp)
fit_cp_linear = function(np.array(temperature), *popt)

plt.figure(1)
plt.plot(temperature,cp,color=\'blue\',linewidth=3)
plt.plot(temperature,fit_cp_linear,color=\'red\',linewidth=3)
plt.legend([\'Actual fit\',\'linear curve fit\'])
plt.grid()
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'specific heat\')
plt.savefig(\'graph_1\')
plt.show()

#quadratic curve
def function(t,a,b,c):
	return a*pow(t,2)+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(function,temperature,cp)
fit_cp_quad = function(np.array(temperature), *popt)

plt.figure(2)
plt.plot(temperature,cp,color=\'blue\',linewidth=3)
plt.plot(temperature,fit_cp_quad,color=\'red\',linewidth=3)
plt.legend([\'Actual fit\',\'quadratic curve fit\'])
plt.grid()
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'specific heat\')
plt.savefig(\'graph_2\')
plt.show()

#cubic curve
def function(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(function,temperature,cp)
fit_cp_cubic = function(np.array(temperature), *popt)

plt.figure(3)
plt.plot(temperature,cp,color=\'blue\',linewidth=3)
plt.plot(temperature,fit_cp_cubic,color=\'red\',linewidth=3)
plt.legend([\'Actual fit\',\'cubic curve fit\'])
plt.grid()
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'specific heat\')
plt.savefig(\'graph_3\')
plt.show()

#power 4 curve
def function(t,a,b,c,d,e):
	return a*pow(t,4)+b*pow(t,3)+c*pow(t,2)+d*t+e
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(function,temperature,cp)
fit_cp_4 = function(np.array(temperature), *popt)

plt.figure(4)
plt.plot(temperature,cp,color=\'blue\',linewidth=3)
plt.plot(temperature,fit_cp_4,color=\'red\',linewidth=3)
plt.legend([\'Actual fit\',\'power 4 curve fit\'])
plt.grid()
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'specific heat\')
plt.savefig(\'graph_4\')
plt.show()	

#power 9 curve
def function(t,a,b,c,d,e,f,g,h,i,j):
	return a*pow(t,9)+b*pow(t,8)+c*pow(t,7)+d*pow(t,6)+e*pow(t,5)+f*pow(t,4)+g*pow(t,3)+h*pow(t,2)+i*t+j
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(function,temperature,cp)
fit_cp_power = function(np.array(temperature), *popt)

plt.figure(5)
plt.plot(temperature,cp,color=\'blue\',linewidth=3)
plt.plot(temperature,fit_cp_power,color=\'red\',linewidth=3)
plt.legend([\'Actual fit\',\'power 9 curve fit\'])
plt.grid()
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'specific heat\')
plt.savefig(\'graph_5\')
plt.show()	

#combination of all curves
plt.figure(6)
plt.plot(temperature,cp,color=\'blue\',linewidth=3)
plt.plot(temperature,fit_cp_linear,color=\'red\',linewidth=3)
plt.plot(temperature,fit_cp_quad,color=\'yellow\',linewidth=3)
plt.plot(temperature,fit_cp_cubic,color=\'black\',linewidth=3)
plt.plot(temperature,fit_cp_4,color=\'green\',linewidth=3)
plt.plot(temperature,fit_cp_power,color=\'orange\',linewidth=3)
plt.legend([\'Actual fit\',\'linear curve fit\',\'quadratic curve fit\',\'cubic curve fit\',\'power 4 curve fit\',\'power 9 curve fit\'])
plt.grid()
plt.xlabel(\'temperature[k]\')
plt.ylabel(\'specific heat\')
plt.savefig(\'graph_6\')
plt.show()

RESULTS OF THE PROGRAM:

For linear polynomial:

\"\"

For quadratic polynomial:

\"\"

For cubic polynomial:

\"\"

For polynomial of degree 4:

\"\"

For polynomial of degree 9:

\"\"

combination of all curves:

\"\"

CONCLUSION:

When we compare the graphs of linear polynomial and cubic polynomial, we can see that cubic is much better than linear.

In order to improve the curve fit we can increase the degree of the polynomial in this case polynomial of degree 9 showed perfect curve 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.