Challenge

Week 5 - Curve fitting

Aim:

To write a python code to fit a linear and cubic polynomial for the Cp data.

Objective:

To plot the actual data and the fitted curve to compare accuracy

Equations:

Linear equation: `xt+y`

Cubic equation: `xt^3 + yt^2 + zt + xyz`

Main program:

"""
python program to perform curve fit for linear and cubic functions
-Raaghul V
"""

#importing necessary modules
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

#linear function 
def lin_fun(t,x,y):
	return (x*t)+y
#Cubic Function
def cub_fun(t,x,y,z,xyz):
	return (x*pow(t,3)) + (y*pow(t,2)) + (z*t) + xyz

#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
    
t,cp = read_file()
popt,pcov = curve_fit(cub_fun, t, cp)
fit_cp = cub_fun(np.array(t), *popt) #Here *popt contains the values for the constants present in our function or equation to be fitted.

#Plotting the curves 
plt.plot(t, cp,)
plt.plot(t, fit_cp,)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature T (K)')
plt.ylabel('Specific heat C_p (J)')
plt.title("Curve fitting for a cubic function")
plt.savefig("CUBIC FUNCTION")
plt.show()

popt, pcov = curve_fit(lin_fun, t, cp) 
fit_cp = lin_fun(np.array(t), *popt) 


#Plotting the curves 
plt.plot(t, cp,)
plt.plot(t, fit_cp,)
plt.legend(['Actual data','Curve fit'])
plt.xlabel('Temperature T (K)')
plt.ylabel('Specific heat C_p (J)')
plt.title("Curve fitting for a linear function")
plt.savefig("LINEAR FUNCTION")
plt.show()


#Plot for comparison
popt1, pcov1 = curve_fit(lin_fun, t, cp) 
popt2, pcov2 = curve_fit(cub_fun, t, cp)
fit_cp_lin = lin_fun(np.array(t), *popt1)
fit_cp_cub = cub_fun(np.array(t), *popt2)

#Plotting the curves 
plt.plot(t, cp,)
plt.plot(t, fit_cp_lin,)
plt.plot(t, fit_cp_cub,)
plt.legend(['Actual data','Curve fit(Linear)','Curve fit(Cubic)'])
plt.xlabel('Temperature T (K)')
plt.ylabel('Specific heat C_p (J)')
plt.title("Comparing the curve fitting of linear and cubic fuctions with the orignal function")
plt.savefig("Comparison")
plt.show()
    

Procedure:

  1. The neccesary libraries NumPy, Scipy.optimize.curve_fit, and matplotlib.pyplot are imported.
  2. User-defined functions are created inorder to represent the linear and polynomial equation.
  3. A user-defined function is also created for reading the neccesary thermodynamic data from the file 'data.txt'.
  4. The respective curve fit functions are defined and the respective graphs are plotted.

Results:

Conclusion:

From the graphs above, we can conclude that increasing the order of the polynomial, inturn improves the fitting of the curve withthe orignal data.

Questions:

  1. What does popt and pcov mean?

popt and pcov are parameters of Scipy.optimize.curve_fit Module.

popt: It is an array that provides an optimal value so that the sum of the squared residuals of the function. In general the return value ‘popt’ contains the best fit values of the parameters.

pcov: It contains the covariance matrix for the fit parameters. In general, the ‘pcov’ variable contains the covariance matrix, which indicates the uncertainties and correlations between parameters. This is most useful when the data has uncertainties.

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

NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a NumPy ‘ndarray’ object by using the array() function.

  1. What does the * in *popt mean?

The star (*) is used as a reference or as an argument to a function. The star (*) notation will expand a list of values into the arguments of the function. This is useful if the function has more than one or two parameters. In general, the star (*) notation is used so that the variable which is placed after the star (*) is being referenced. The change occurred in the popt is reflected in the original popt value.

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

The results for the cubic polynomila were good as we were able to fit that curve almost perfectly.The linear polynomial is obviously going to be a straight line and cannot be fitted perfectly

  1. What needs to be done to make the curve fit perfectly?

The curve fit can never be perfect. The main reason for that is the actual Experimental value and the ideal curve-fit value always vary. However, the value of actual data may come close to the ideal curve fit value. This can be seen by the code and graph shown. As the order of the equations increase, the value gets closer to the ideal value.

RESULT:

Hence, using the above code, we were able to perform curve fitting on a Cubic 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.