Challenge

Week 5 - Curve fitting

Objective:- In the Project, we will write a python program to fitting a curve to data.

Theory:-

popt:- It is an array of Optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized.

pcov:- 2-D array of the estimated covariance of popt.

np.array(temperature) will create a numpy array.

*popt * represents the reference of popt variable.

Python script:-

#Python program for curve fitting to given data.

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

#curve fit function
def func(t,a,b,c,d):    #here equation is function of 't',and 'a,b,c,d are co-efficient
    return a*pow(t,3)+b*pow(t,2)+c*t+d

#reading data_file
                      
def read_file():      
    temperature=[]
    cp=[]
    for line in open('data','r'):                       #reading each line of file
        temperature.append(float(line.split(',')[0]))   #storing the vlues of temperature in temperature array
        cp.append(float(line.split(',')[1]))            #storing the vlues of cp in array cp
    return [temperature,cp]


#calling of function
temperature,cp=read_file()

popt,pcov=curve_fit(func,temperature,cp)
print(popt)
print(pcov)
fit_cp=func(np.array(temperature),*popt)

plt.plot(temperature,cp,linewidth=2,color='red')
plt.plot(temperature,fit_cp,linewidth=2,color='yellow') 
plt.legend(['actual data','curve fit'])
plt.xlabel('Temperature[k]')
plt.ylabel('Cp') 
plt.show()

Output:-

Thus we achieved a curve very close to actual curve.

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.