Project

curve fitting in python

Introduction:

This assignment is making a curve fit for the data of temp vs CP using the scipy module by least square method.thus we can represent an actual phenomenon using a polynomial equation. This method of making a curve fit help us in understanding various aspect of performing a calculation with the help of it.

Explanation:

Import all the necessary modules needed for making the curve fit of the given data ,then define the polynomial function we want to use to make the curve fit . open the file where the data are stored and the save them in list so that they can be accessed later .we have to find out the constants to the polynomial equation we defined using the curvefit() ,the parameters passed are the polynomial function an the two list values that we extracted from the data file .the return value of the function is stored in popt and pcov

popt-is a list containing constants for the polynomial eqn

pcov-contains the covariance matrix of popt

*popt-is for data unpacking

in order to get a better curve fit we have to increase the order of the polynomial or split the function into multiple segments and fit a curve

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


def func(x,a,b):#linear function
    return (x*a+b)

def func1(x,a,b,c,d):#cubic function
    return (a*pow(x,3)+b*pow(x,2)+x*c+d)
def read_file():
        temp=[]
        cp=[]
        for line in open('data','r'):
            value=line.split(',')
            temp.append(float(value[0]))
            cp.append(float(value[1]))
        return [temp,cp] 

[temp,cp]=read_file()
popt,pcov=curve_fit(func,temp,cp)
popt1,pcov1=curve_fit(func1,temp,cp)
fit_cp=func(np.array(temp),*popt) #*popt is for unpacking the list 
fit_cp1=func1(np.array(temp),*popt1)

plt.plot(temp,cp,color="blue",linewidth=3)
plt.plot(temp,fit_cp,color="red",linewidth=3)
plt.plot(temp,fit_cp1,color="green",linewidth=3)
plt.legend(['actual data','curve fit(linear)','curve fit(cubic)'])
plt.xlabel('temprature[k]')
plt.ylabel('cp')
plt.show()

conclusion:

the curve fit of the following data is sucessufully executed with the help of the above given code

plots:

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.