Project

Curve fitting in Python using SCIPY

1. What does popt and pcov mean?

popt:

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

pcov:

The pcov variable contains the covariance matrix, which indicates the uncertainties and correlations between parameters. This is mostly useful when the data has uncertainties.

2. What does np.array(temperature) do?

It creates the array of temperature values from the data file using numpy library.

3. What does the * in *popt mean?

* as used in function declaration allows variable number of arguments passed from calling environment.

Code for curve fitting

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

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

# functio to read a data file and convert them into arrays of specific data
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]

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

plt.plot(temperature,cp,color = "blue")
plt.plot(temperature,fit_cp,color = "red")
plt.legend(['Actual data','linear curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('specific heat at constant pressure')
plt.savefig('linear curve fit')
plt.show()


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

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]

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

plt.plot(temperature,cp,color = "blue")
plt.plot(temperature,fit_cp,color = "red")
plt.legend(['Actual data','cubical curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('specific heat at constant pressure')
plt.savefig('cubical curve fit')
plt.show()



Linear curve fitting plot

Cubical curve fitting

Conclusion:

As the degree of fitting function increases, the ressemblence to the original data increases. So cubical fitting gives better results than linear fitting. And the degree of the fitting function can be increased further to get better results.

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.