Challenge

Week 5 - Curve fitting

Curve fitting can be defined as the process of constructing a curve or mathematical function that has the best fit to a series of data points, subject to constraints.

In this project, the curve for specific heat as a function of temperature will be plotted and the plot will be compared with the actual plot.

What is popt ?

it gives an array with the optimal values for the parameters so that the sum of the squared residuals of data is minimized.

pcov :- It is a 2D array with the estimated covariance of the parameters in popt. It can be used to calculate the standard deviation errors of popt.

np.array(temperature):- This function stores the values of temperature in the form of array and passes it to the function numpy.

*in* popt :- It stores the values of the constant parameters (a,b,c) in the array popt.

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

#Curve fit linear function
def function(t,a,c):
return a*t+c
#reading thermodynamic data file
def read_file():
temperature=[]
cp=[]
for line in open('data','r'):
values=line.split(',')
cp.append(float(values[1]))
return[temperature,cp]

#Main program for linear function
temperature,cp = read_file()
popt,pcov=curve_fit(function,temperature,cp)
fit_cp=function(np.array(temperature),*popt)

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

plt.show()

#Curve fit for cubic equation

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

#Curve fit function
def func_cubic(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d

#reading thermodynamic 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
temperature,cp = read_file
popt,pcov=curve_fit(func_cubic,temperature,cp)
fit_cp=func_cubic(np.array(temperature),*popt)

plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cp,color='red',linewidth=3)
plt.title('specific heat Vs temperature')
plt.legend(['actual data','Curve fit'])
plt.xlabel('temperature[K]')
plt.ylabel('cp')
plt.show()

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.