Week 5 - Curve fitting
Aim/Objective: To perform curve fitting using Python
Theory:
Curve fitting is the process of construction of a curve , or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and the parameter values, etc. It is highly effective in the mathematical modeling of some natural processes.
Program:
For Linear:
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'): # opening a file and reading the data
values = line.split(',') # splitting line using comma
temp .append(float(values[0])) # appending or adding data into the temp file
cp.append(float(values[1]))
return [temp,cp]
temp,cp = read_file() # calling the function read_file and storing the values into temp & cp
popt,pcov = curve_fit(func,temp,cp) # popt = coefficients i.e a & b , pcov = estimated covarience of popt
fit_cp = func(np.array(temp), *popt) # we are passing temp as numpy array
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()
For Cubic:
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'): # opening a file and reading the data
values = line.split(',') # splitting line using comma
temp .append(float(values[0])) # appending or adding data into the temp file
cp.append(float(values[1]))
return [temp,cp]
temp,cp = read_file()
popt,pcov = curve_fit(func,temp,cp) # popt = coefficients i.e a , b , c & d , pcov = estimated covarience of popt
fit_cp = func(np.array(temp), *popt) # we are passing temp as numpy array
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()