Challenge

Week 5 - Curve fitting

Curve fitting using Python

Aim: To fit a curve for linear and cubic polynomial of the data.

Theory:

Curve Fitting

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. 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.

The first degree polynomial equation

`y=ax +b`

is a line with slope a. A line will connect any two points, so a first degree polynomial equation is an exact fit through any two points with distinct x coordinates.

If the order of the equation is increased to a second degree polynomial

`y=ax ^2+bx+c`

This will exactly fit a simple curve to three points.

If the order of the equation is increased to a third degree polynomial

`y=ax^3+bx ^2+cx+d`

This will exactly fit four points. A more general statement would be to say it will exactly fit four constraints.

Here, red line is a first degree polynomial, green line is second degree, orange line is third degree and blue is fourth degree.

In this project, curve fitting is done on linear and cubic polynomial.

Actual data of the fit is taken from ‘data’ file which contains values of specific heat at particular temperature. First, functions are made for both linear and cubic polynomials to calculate value of variables. Next, by reading the file mentioned above, values of temperature and specific heat are stored in the empty arrays created.

popt and pcov are used to store the values of variables and curves are plotted.

Program:

# A program for Curve fitting

# Importing libraries
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

# Curve fit functions

# Linear function
def func_l(t,a,b):
	A = a*t+b
	return A

# Cubic function
def func_c(t,a,b,c,d):
	B = a*pow(t,3)+b*pow(t,2)+c*t+d
	return B

# Reading data file
def file():

	# Creating empy arrays
	temperature = []
	cp = []
	# Loop
	for line in open('data','r'): 
		# Splitting temperature and cp values
		values = line.split(',')
		# Appending calculated values
		temperature.append(float(values[0]))
		cp.append (float(values [1]))
	return [temperature,cp]

# Main Program

temperature,cp = file()
# Linear curve fitting
popt,pcov = curve_fit(func_l,temperature,cp)
fit_l = func_l(np.array(temperature),*popt)

# Plotting curves
plt.figure()
plt.plot(temperature,cp,'--')
plt.plot(temperature,fit_l)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature (K)')
plt.ylabel('Cp (KJ/KgK)')
plt.title('Linear Curve fitting')
plt.savefig('Linear Curve fitting')
plt.show()

# Cubic curve fitting
popt,pcov = curve_fit(func_c,temperature,cp)
fit_c = func_c(np.array (temperature),*popt)

# Plotting curves
plt.figure()
plt.plot(temperature,cp,'--')
plt.plot(temperature,fit_c,)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature (K)')
plt.ylabel('Cp (KJ/KgK)')
plt.title('Cubic Curve fitting')
plt.savefig('Cubic Curve fitting')
plt.show()

# End

Results:

Que. What does popt and pcov means?

Ans: popt is an array which optimizes values for the parameters so that the sum of the squared error of the function is minimized.

pcov is a 2d array which is the estimated covariance of popt. The diagonals provide the variance of the parameter estimate.

Que. 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. The number of dimensions is the rank of the array. Here, np.array(temperature) is converting the values of temperature from list to ndarray so that mathematical operations can be done on the values.

Que. What does the * in *popt mean?

Ans: The * in *popt is used to access all the values of variables stored in popt.

Que. What needs to be done in order to make the curve fit perfect?

Ans: To make a curve fit perfect, all errors should be considered. A perfect fit should fit the original curve perfectly. Perfect fit is always a best fit but a best fit cannot be a perfect fit.

Conclusion:

It is observed that the best fit can be obtained by increasing the degree of polynomial. But to obtain the perfect fit, errors should be considered.

Reference:

https://en.wikipedia.org/wiki/Curve_fitting

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.