Project

Curve Fitting

1. What does popt and pcov mean?

popt- An array of optimal values for the parameters which minimizes the sum of squares of residuals.

pcov-2d array which contains the estimated covariance of popt. The diagonals provide the variance of the parameter estimate.

2. What does np.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.

3. What does the * in *popt mean?

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

4. Write code to fit a linear and cubic polynomial for the Cp data. Explain if your results are good or bad.

Code:

# Curve fitting
# By: Anubrat Padhee

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

# Defining curve fitting function 1
def func1(t,a,b):
	return a*t+b
# Defining curve fitting function 2	
def func2(t,c,d,e,f):
	return c*pow(t,3)+d*pow(t,2)+e*t+f

# File reading function
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()
popt1,pcov1=curve_fit(func1,temperature,cp)
popt2,pcov2=curve_fit(func2,temperature,cp)
fit_cp1=func1(np.array(temperature),*popt1)
fit_cp2=func2(np.array(temperature),*popt2)	

# Plotting actual fit and curve fit for linear curve fit function
plt.figure()
plt.plot(temperature,cp,color='blue',linewidth=3)	
plt.plot(temperature,fit_cp1,color='red',linewidth=3)
plt.legend(['Actual fit','Curve fit'])
plt.xlabel("Temperature[k]")
plt.ylabel("Specific heat")	
plt.title("Linear fit")
plt.show()

# Plotting actual fit and curve fit for cubic curve fit function
plt.figure()
plt.plot(temperature,cp,color='blue',linewidth=3)	
plt.plot(temperature,fit_cp2,color='red',linewidth=3)
plt.legend(['Actual fit','Curve fit'])
plt.xlabel("Temperature[k]")
plt.ylabel("Specific heat")	
plt.title("Cubic fit")
plt.show()

Output:

Explanation of results:

The cubic fit is more accurate than linear fit.

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

We can increase the degree of the polynomial for a better fit

We can also part the data into various segments and curve fit them using different degree of 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.