Challenge

Week 5 - Curve fitting

AIM: To write the Python program to fit a linear and cubic polynomial for the Cp 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. It is needed to predict the future values comparing with current data.

Curve fitting examines the relationship between one or more predictors (independent variables) and a response variable (dependent variable), with the goal of defining a "best fit" model of the relationship.

The most common way to fit the curve is using polynomial terms, such as linear ,square , cubic equations. We increase the order to get to increase the bends to get fit the curve as close as previous data. Hence here also we use cubic polynomial. While using increased order polynomial it might happen that it gives warning . But keeping same degree we can eliminate the warning by doing centering and scaling so that he curve can be close to perfectively fit.

What do popt and pcov mean?

popt- It helps to minimize the sum of the squared error of function data by an array of optimal values of parameters

pcov-The estimated covariance of popt or in other words tells that how far the variables may change together. The diagonal
provides the variance of the parameter estimate.

What does np.array(temperature) do?

The temperature values will be taken and pass as a numpy array to perform certain mathematical operations.

What does the * in *popt mean?

This is used to tell that this is stored in a popt array. It contains the value of coefficients and refers to these values.

Program:-

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.optimize import curve_fit
#curve fit
def func(t,a,b,c,d):
	return  a*pow(t,3)+b*pow(t,2)+c*t+d 
#reading thermodynamic data file
def read_file():
	temprature = []
	cp = []
	for line in open('data1', 'r'):
		values = line.split(',')
		temprature.append(float(values[0]))
		cp.append(float(values[1]))
	return [temprature,cp]

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

plt.plot(temperature, cp,, linewidth=3)
plt.plot(temperature, fit_cp, color='red',linewidth=3)
plt.xlabel('temperature[k]')
plt.ylabel('cp')
plt.title('Specific Heat Vs Temperature')
plt.legend(['Actual data','Curve fit'])
plt.grid()
plt.show()

Result:

From the basis of MATLAB coding i had a knowledge that this problem is satisfied for 3 order equation, so i directly stated with 3 order euation.

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.