Project

Curve Fitting Python

1 What does popt and pcov mean?

Ans POPT is the output is an array with the values for the parameter used above so that the sum of the squares residuals of data in minimised.

2 What does np.array(temperature) do?

Ans It stores the values of temperature in the form of array and passes to function numpy.

3 What does the *in*popt mean?

Ans IT stores the values of the constant parameter in popt array.

Code for the linear curve fit.

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(\'data\',\'r\'):
			values = line.split(\',\')
			temp.append(float(values[0]))
			cp.append(float(values[1]))
	return [temp,cp]
	
temperature,cp=read_file()

popt,pcov=curve_fit(func,temperature,cp)

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

plt.figure()
plt.plot(temperature,cp,\'-b\',label=\'orignal data\')
plt.plot(temperature,fit_cp,\'r\',label=\'linear curve fit data\')
plt.xlabel(\'temperature\')
plt.ylabel(\'cp\')
plt.legend(loc=\'best\')
plt.savefig(\'cubic.png\')
plt.show()				

OUTPUT

CODE for cubic curve fit

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

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

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

popt,pcov=curve_fit(func,temperature,cp)

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

plt.figure()
plt.plot(temperature,cp,\'-b\',label=\'orignal data\')
plt.plot(temperature,fit_cp,\'r\',label=\'cubic curve fit data\')
plt.xlabel(\'temperature\')
plt.ylabel(\'cp\')
plt.legend(loc=\'best\')
plt.savefig(\'cubic.png\')
plt.show()				

OUTPUT

EXPLANATION

  • Firstly we import the numpy,matplotlib,scipy.optimize from the library.
  • Define the polynomial function for the cubic and linear function.
  • Define the function to read the data file.
  • In that two empty array as temp and cp for defining values.
  • FUnction calling as the temperature,cp=read file.
  • Using the curve fit function for the cubic and linear curve fit.
  • Calculating the value of cp.
  • plot the graph as per the written code.
  • As the cubic curve is good because as for the curve fit higher order polynomial is taken.
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.