Challenge

Week 5 - Curve fitting

1.What does popt and pcov mean?

popt stores the coefficients of the polynomial .Optimal values for the parameters so that the sum of the squared residuals is minimized.

pcov variable contains the covariance matrix, which indicates the uncertainties and correlations between parameters. This is mostly useful when the data has uncertainties.

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

  • np.array is a multidimensional array object
  • Every array entry must correspond to preset data types (simple types like float, int etc. or complex types like strings, tupels)
  • an np.array acts as container for data to be passed between algorithms

3.What does the * in *popt mean?

The special syntax * definitions in python is used to pass a variable number of arguments to a function.

4.Write code to fit a linear and cubic polynomial for the Cp data

AIM

Code to fit a linear and cubic polynomial for the Cp data.

INTRODUCTION

Curve fitting is the process of constructing a curve, or mathematical function, that has the best fit to a series of datapoints, possibly subject to constraints.

Curve fitting is one of the most powerful and most widely used analysis tools in Origin. 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 first degree polynomial equation cp=a*T + 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, the following results:

cp=a*T^2 + b*T + c This will exactly fit a simple curve to three points.

If the order of the equation is increased to a third degree polynomial, the following is obtained: cp= a*T^3 + b*T^2 + ct +d ;.This will exactly fit four points.

Fitting other functions to data points

Other types of curves, such as trignomentric functions (such as sine and cosine), may also be used, in certain cases.

Fitting a circle by geomentric fit

The method elegantly transforms the ordinarily non-linear problem into a linear problem that can be solved without using iterative numerical methods, and is hence much faster than previous techniques.

Fitting a ellipse by geomentric fit

The above technique is extended to general ellipses by adding a non-linear step, resulting in a method that is fast, yet finds visually pleasing ellipses of arbitrary orientation and displacement.

Finally This can be applied to the surfaces.

Evaluating Goodness of Fit

  • The sum of squares due to error (SSE)
  • R-square
  • Adjusted R-square
  • Root mean squared error (RMSE)

PROGRAM

import math
import matplotlib.pyplot as plt  
import numpy as np 

from scipy.optimize import curve_fit
#Reading the thermodynamic data file
temperature=[]
c_p=[]
a=open('data','r')

for line in a:
	values=line.split(',')
	temperature.append(float(values[0]))
	c_p.append(float(values[1]))
#compare  linear polynomial with original data

def poly1(t,a,b):
	return a*t+b


popt,pcov=curve_fit(poly1,temperature,c_p)
predicted_cp1=poly1(np.array(temperature),*popt)

plt.figure(1)
plt.plot(temperature,c_p,linewidth=3,color='green')
plt.plot(temperature,predicted_cp1,linewidth=3,color='red')
plt.legend(["actual data", "linear curve fit"])
plt.title('specific heat vs temperature(linear fit)')
plt.xlabel('temperature',color='b')
plt.ylabel('specific heat',color='b')
plt.show()
#compare 2nd degree polynomial with original data
def poly2(t,a,b,c):
	return a*pow(t,2)+b*t+c

popt2,pcov2=curve_fit(poly2,temperature,c_p)

predicted_cp2=poly2(np.array(temperature),*popt2)
plt.figure(2)
plt.plot(temperature,c_p,color='green',linewidth=3 )
plt.plot(temperature,predicted_cp2,color='red',linewidth=3)
plt.title('specific heat vs temperature(2nd order fit)')
plt.legend(["actual data", "2nd order curve fit"])
plt.xlabel('temperature',color='b')
plt.ylabel('specific heat',color='b')
plt.show()

#compare cubic polynomial with original data
def poly3(t,a,b,c,d):
	return a*pow(t,3)+b*pow(t,2)+c*t+d

popt3,pcov3=curve_fit(poly3,temperature,c_p)

predicted_cp3=poly3(np.array(temperature),*popt3)
plt.figure(3)
plt.plot(temperature,c_p,color='green',linewidth=3)
plt.plot(temperature,predicted_cp3,color='red',linewidth=3)
plt.legend(["actual data", "cubic curve fit"])
plt.title('specific heat vs temperature(cubic fit)')
plt.xlabel('temperature',color='b')
plt.ylabel('specific heat',color='b')
plt.show()

PROCEDURE

Curve fit is a mathematical function we can assume as quadratic cubic or nth order polynomial we can take the function and find the best values of coefficient to closely represent the data.

  • Intially we are importing math and mathplotlib
  • Matplotlib is a plotting library for the Python programming language
  • The file should be opened in read mode by a=open('data','r').
  • Data we are taking is specific heat(cp) as a function of temperature .cp varies with temperature.
  • Then for loop is used and we are splitting values and cp ,temperature values are stored.
  • A function is defined The arguments to the function and parameters are given
  • The curve_fit used to find the best-fit parameters using a least-squares fit.
  • The curve_fit function returns two items, which we can popt and pcov. The popt argument are the best-fit paramters for a and b.
  • Finally we are comparing curve fit for 1 degree polynomial with original data.(cp VS temperature).
  • Same procedure is done for quadratic and cubic polynomial and compared with original data.(cp VS temperature).

RESULTS

The cubic fit is better than linear fit .

5.How to make a curve fit perfectly?

Perfect fit means, the curve should fit the original curve without showing any errors

R2 an indicator of the "goodness of fit is exactly 1.0000 when the fit is perfect, less than that when the fit is imperfect

By increasing the degree of polynomial we can make the curve smoothen.

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.