Challenge

Week 5 - Curve fitting

Aim -

To write python code for curve fitting.

Introduction -

Curve fitting in a process of fitting fuction in polynomial.data points can be fitted in nth order polynomial and ploted .curve fitting help in data prediction.

What does popt and pcov mean ?

popt is an array that stores the value of the coefficients that are being passed in given function and pcov is an two dimensional array that stores the values of estimated covariance of popt i.e the coefficients.

What does np.array(temperature ) do?

It is used for passing temperature value as numpy array

What does the *in*popt mean ?

'*' in *popt help us to refer coefficients in a given equattion

Codes to fit a linear and cubic polynomial for the Cp data:

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

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

def read_file():
    temp = []
    cp =[]
    for line in open ('datafile','r'):
        values =line.split(',')
        temp.append(float(values[0]))
        cp.append(float(values[1]))
    return [temp,cp]

temp,cp = read_file()
popt,pcov = curve_fit(func,temp,cp)
fit_cp =func(np.array(temp),*popt)

plt.plot(temp,cp,color ='red',linewidth =3)
plt.plot(temp,fit_cp,color ='blue',linewidth =3)
plt.legend(['actual data','curve fit data'])
plt.xlabel('temperature[k]')
plt.ylabel('cp')
plt.show()

output -

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

def func(t,c,a,b,d):
    return a*pow(t,3)+b*pow(t,2)+c*t+d

def read_file():
    temp =[]
    cp =[]
    for line in open ('datafile','r'):
        values =line.split(',')
        temp.append(float(values[0]))
        cp.append(float(values[1]))
    return [temp,cp]
temp,cp =read_file()
popt,pcov =curve_fit(func,temp,cp)
fit_cp = func(np.array(temp),*popt)

plt.plot(temp,cp,color ='red',linewidth =3)
plt.plot(temp,fit_cp,color ='blue',linewidth =3)
plt.legend(['actual data','curve fit data'])
plt.xlabel('temperature [k]')
plt.ylabel('cp')
plt.show()

output -

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

by either increasing order of polynomial or by using splitwise 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.