Project

Curve fitting

1. popt and pcov

\'popt\' is the array that contains the optimal parameters of the coefficients of the curv fit equation used.

\'pcov\' is a 2D array that contains the estimated covariance of the parameters in \'popt\'.

2. np.array(temperature)

\'np.array()\' is used to create a numpy array while the temperature values are passed as the data of the array.

3. *popt

\'*popt\' is used to expand the list of values stored in the array \'popt\' into the arguments of the function.

4. By using linear equation for curve fit results do not appear to be good and there is a lot of variation in accordance with the actual data.

Cubic curve fit shows better results as it captures majority of the actual data and gives us a good fit.

5. As we keep on increasing the order of the curve it can capture the data with a perfect fit but it also increases the no. of constants used means more complexity. Moreover it may result in curve overfit and may therefore fail to fit additional data or predict future observations reliably. The choice of best fit always depends on the explanation of the actual behaviour of the data. The data can be divided into smaller proportions to achieve a better fit. Therefore, validation techniques such as cross validation are used to solve this problem. In cross validation, the data is split into some finite no. of folds. Then, the first fold is used to validate the model. After that, the next fold is used for validation and so on. Finally the mean of errors is calculated. The model with lower mean error is chosen.

Output:

1. Linear

\"\"

2. Cubic

\"\"

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

# Curve fit function - Linear
def f1(t,a,b):
    return a*t + b

# Curve fit function - cubic
def f3(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\'):
        value = line.split(\',\')
        temp.append(float(value[0]))
        Cp.append(float(value[1]))
        
    return[temp,Cp] 
    
#main program
temp, Cp = read_file()
popt, pcov = curve_fit(f1, temp, Cp)
fit_Cp1 = f1(np.array(temp), *popt)

popt, pcov = curve_fit(f3, temp, Cp)
fit_Cp3 = f3(np.array(temp), *popt)

plt.figure(1)
plt.plot(temp,Cp)
plt.plot(temp,fit_Cp1)
plt.legend([\'Actual Data\', \'Curve Fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'Cp\')
plt.show()

plt.figure(2)
plt.plot(temp,Cp)
plt.plot(temp,fit_Cp3)
plt.legend([\'Actual Data\', \'Curve Fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'Cp\')
plt.show()
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.