Challenge

Week 5 - Curve fitting

AIM: Curve fitting using Python.

Objectives of the Project:

  1. Write a code to fit a linear and cubic polynomial for the cp data.
  2. Plot the linear and cubic fit curve along with the raw data points.

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

A related topic is regression analysis, 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 uncertainty since it may reflect the method used to construct the curve as much as it reflects the observed data.

Fitting functions to data points,

Most commonly, one fits a function of the form y=f(x)

  • 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, the following results as y=ax2+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, the following is obtained as y=ax3+bx2+cx+d.This will exactly fit four points.

Body of the Content:

PYTHON is used to display the code of the program.(The code itself explain in program by creating comments)

  • Coding to Plot Linear Curve Fit:
# A Program to fit the linear polynomial curve

# Importing math library 

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

# Linear curve fit function

def linear(t,a,b):                                       # Defining the linear function with variable and coefficients
	return a*t+b                                         # Return the values of linear function to get an output


# Reading thermodynamic data file

def read_file():                                         # Reading the given thermodynamic data file
	temperature=[]                                       # To create an array of temperature
	cp=[]                                                # To create an array of cp
	for line in open('data','r'):                        # To open the file of name 'data' and read each line of it with the helo of for loop
		values=line.split(',')                           # To split the line with ','
		temperature.append(float(values[0]))             # .append is used to store the calculated values of column 1 in temperature array
		cp.append(float(values[1]))                      # .append is used to store the calculated values of column 2 in cp array

	return [temperature,cp]                              # Return the values of temperature and cp as an output 

# Main Program

temperature,cp=read_file()                              # To read the data of temperature and cp values which is return as an output
popt,pcov=curve_fit(linear,temperature,cp)              # The curve_fit function calculate the coeff values and popt as an output of it.pcov-is the covariance matrix showing the uncertainty and interdependence of each parameter in popt 
fit_cp=linear(np.array(temperature), *popt)             # passing the entire temperature with the help of np.array and *popt contains the values of coeffs. 


plt.plot(temperature,cp,color="blue",linewidth=3)       # Plot the graph for temperature vs cp with raw data points
plt.plot(temperature,fit_cp,color="red",linewidth=3)    # Plot the graph for temperature vs fit_cp with the help of linear curve points
plt.legend(['Actual data','Linear Curve fit'])          # To give specific name to each curve
plt.xlabel('Temperature [K]')                           # To give label to x-axis as 'Temperature [K]'
plt.ylabel('Specific Heat')                             # To give label to y-axis as 'Specific Heat'
plt.show()                                              # To show the graph

  • Output :

  • Coding to Plot Cubic Curve Fit:
# A Program to fit the cubic polynomial curve

# Importing math library 

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

# Cubic curve fit function

def cubic(t,a,b,c,d):                                    # Defining the cubic function with variable and coefficients
	return a*pow(t,3)+b*pow(t,2)+c*t+d                   # Return the values of cubic function to get an output


# Reading thermodynamic data file

def read_file():                                         # Reading the given thermodynamic data file
	temperature=[]                                       # To create an array of temperature
	cp=[]                                                # To create an array of cp
	for line in open('data','r'):                        # To open the file of name 'data' and read each line of it with the helo of for loop
		values=line.split(',')                           # To split the line with ','
		temperature.append(float(values[0]))             # .append is used to store the calculated values of column 1 in temperature array
		cp.append(float(values[1]))                      # .append is used to store the calculated values of column 2 in cp array

	return [temperature,cp]                              # Return the values of temperature and cp as an output 

# Main Program

temperature,cp=read_file()                              # To read the data of temperature and cp values which is return as an output
popt,pcov=curve_fit(cubic,temperature,cp)               # The curve_fit function calculate the coeff values and popt as an output of it.pcov-is the covariance matrix showing the uncertainty and interdependence of each parameter in popt 
fit_cp=cubic(np.array(temperature), *popt)              # passing the entire temperature with the help of np.array and *popt contains the values of coeffs. 

plt.plot(temperature,cp,color="blue",linewidth=3)       # Plot the graph for temperature vs cp with raw data points
plt.plot(temperature,fit_cp,color="red",linewidth=3)    # Plot the graph for temperature vs fit_cp with the help of cubic curve points
plt.legend(['Actual data','Cubic Curve fit'])           # To give specific name to each curve
plt.xlabel('Temperature [K]')                           # To give label to x-axis as 'Temperature [K]'
plt.ylabel('Specific Heat')                             # To give label to y-axis as 'Specific Heat'
plt.show()                                              # To show the graph

  • Output :

  • Explanation on Result:

From the above two plots, it is observed that the linear curve fit is not smoothly fixed with the original data points whereas the cubic curve fit overlaps with the original data set except some regions. Hence, the results are good because the cubic curve fit is better curve fit than the linear one from obtained outputs.

  • Question Asked:

Que1. What does popt and pcov mean?

Ans: popt-It is a one dimensional array of the best estimates for the parameter values, each entry matches the order in the function definition.

pcov- It is the covariance matrix showing the uncertainty and interdependence of each parameter in popt. We take the diagonal elements as pvar for the variance of each parameter in popt.

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

Ans: np.array- passes the list of temperature to a numpy array.

Que3. What does the * in *popt mean?

Ans: The * notation in *popt will expand a list of values into the arguments of the function. This is useful when your function has more than one or two parameters.It is used to refer those coefficient stored in popt.

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

Ans: By increasing the order of the polynomial, we can get the best curve fit. If we further increase the order of polynomial to 4, then the curve will be more accurate and precise with the original data points than that of the cubic polynomial.

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.