Challenge

Week 5 - Curve fitting

Aim:-

fitting the linear and cubic curve by using python program

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.[4][5] 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:

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, the following is obtained:

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

This will exactly fit four points.

  1. What doespoptand pcov means?

popt : array. Optimal values for the parameters so that the sum of the squared error of f(xdata, *popt) - ydata is minimized. pcov : 2d array. The estimated covariance of popt. The diagonals provide the variance of the parameter estimate.

Pcov-2D array which contains the estimated covariances of popt . The diagonals provide the variance of the parameter estimate covariances of popt . The diagonals provide the variance of the parameter estimate.

  1. What doesnp.array(temperature) do?

np.array- converts the python list of temperature

to a numpy array since operations like pow are

allowed on numpy arrays and not python lists.

  1. What does the * in *popt mean?

*-reference to popt / the values stored in the array

popt.

4. write a code fit linear and cubic polynomial for the cp data.explain results are good or bad

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

# linear Curve fit function
def linear(t,a,b):
	return a*t+b

#Defining third order fit 
#cubic fit	
def cubic(t,a,b,c,d):
	return a*pow(t,3) + b*pow(t,2) + c*t + d

# Reading thermodynamics data file
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]

# Main program
#program for linear fit
temperature, cp = read_file()
popt, pcov = curve_fit(linear, temperature, cp)
fit_cp = linear(np.array(temperature), *popt)
plt.figure(1)
plt.plot(temperature, cp,,linewidth =3)
plt.plot(temperature, fit_cp,, linewidth= 3)
plt.legend(['Actual data','Linear fit'])
plt.title('specific heat vs temperature')
plt.xlabel('temperature [K]',color='b',fontsize =15)
plt.ylabel('Cp',color ='b',fontsize =15)
plt.savefig('Actual data VS linear fit.png')
plt.show()

#program for cubic fit
temperature, cp = read_file()
popt, pcov = curve_fit(cubic, temperature, cp)
fit_cp = cubic(np.array(temperature), *popt)
plt.figure(2)
plt.plot(temperature, cp,,linewidth =3)
plt.plot(temperature, fit_cp,, linewidth= 3)
plt.legend(['Actual data','Cubic fit'])
plt.xlabel('temperature [K]',color='b',fontsize =15)
plt.ylabel('Cp',color ='b',fontsize =15)
plt.title('specific heat vs temperature')
plt.savefig('Actual data VS Cubic fit.png')
plt.show()

Algorithms

  • import the important modules like SciPy ,matplotlib , curve fit etc.
  • Define the function for the linear curve
  • Define the function for the cubic curve
  • Define another function to store the data from file
  • Using split function split the lines in data
  • Store the data into empty arrays named cp, temperature
  • By using popt ,pcov and curve_fit function from scipy fit the curve
  • By using matplotlib module plot the graphs
  • By using matplotlib provide title , label, lagend to plots
  • Save the plots.

Plots:

Linear curve fit

Cubic curve fit

Result:-

results are good.....

By increasing the order of polynomial we can make curve perfect

5.what need to do to make curve fit perfect

by increasing order polynomial we can make curve fit perfect.

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.