Challenge

Week 5 - Curve fitting

Aim: To write a code to fit a linear and cubic polynomial for the Cp data and to Plot the linear and cubic fit curves along with the raw data points.

Theory: Curve fits are very useful as they help to describe how the data changes Mathematically. We can perform additional Mathematical operation which might not be possible in the initial data set.

Curve fitting is the process of constructing a curve, or Mathematical function that has the best fit to a series of data points possibly subject to constraints. It is highly effective in Mathematical modeling of some natural processes.

The first degree polynomial equation(linear) is a line with slope 'a'. A line will connect any two points, so a first degree polynomial equation is an exact fit through any two points with distinct x coordinates.

The second degree polynomial equation(quadratic) This will exactly fit a simple curve to three points.

The third degree polynomial equation(Cubic) This will exactly fit the curve to four points.

1]. What does popt and pcov mean?

popt gives the values of coefficients a,b,c in the equation, It stores the values of coefficients in the form of an array.

pcov means its a covariance matrix. It has the estimated values of the covariance parameters of popt, which is used to find the deviation parameters from the mean value.

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

The function np.array is used to perform Mathematical and logical operations to each values in the array.

3]. What does the * in *popt mean?

The * in the *popt is used to unpack all the values in popt in order to pass multiple variables in to function

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

a)Linear polynomial Fit

# Program for linear curve fitting

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

# Curve fit function(liner)


def func(t,a,b,):
	return a*t + b

#  Reading the Thermodynamics data files

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
temperature, cp = read_file()
popt,pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array (temperature), *popt)
#print(popt)
#print(pcov)


plt.plot(temperature, cp, color='blue',linewidth=3)
plt.plot(temperature,fit_cp,color='red' , linewidth=3)
plt.legend(['Actual data','Linear curve fit'])
plt.xlabel('Temperature[k]')
plt.ylabel('specific heat at constant pressure Cp')
plt.savefig('plot 1')
plt.grid()
plt.show()


# Calculation of the R-square parameter

SSE = np.sum(pow(np.array((np.array(cp)-np.array(fit_cp))),2))
SSR = np.sum(pow((np.array(np.array(fit_cp)-np.mean(cp))),2))
SST = SSE + SSR

R_square = SSR/SST

print(R_square)


OUTPUT :

Plot :

b)Cubic Polynomial fit

# Program for cubic curve fitting

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

# Curve fit function(cubic)


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

#  Reading the Thermodynamics data files

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
temperature, cp = read_file()
popt,pcov = curve_fit(func,temperature,cp)
fit_cp = func(np.array (temperature), *popt)
#print(popt)
#print(pcov)


plt.plot(temperature, cp, color='blue',linewidth=3)
plt.plot(temperature,fit_cp,color='red' , linewidth=3)
plt.legend(['Actual data','Cubic curve fit'])
plt.xlabel('Temperature[k]')
plt.ylabel('specific heat at constant pressure Cp')
plt.savefig('plot 1')
plt.grid()
plt.show()

# Calculation of the R-square parameter

SSE = np.sum(pow(np.array((np.array(cp)-np.array(fit_cp))),2))
SSR = np.sum(pow((np.array(np.array(fit_cp)-np.mean(cp))),2))
SST = SSE + SSR

R_square = SSR/SST

print(R_square)

OUTPUT:

Plot :

5].How to get the best fit?


Consider the general form for a polynomial of order j

`f(x)=a0+a1x+a2x2+a3x3+....+ajxj`
Let this be the equation for the curve fit. The curve that gives minimum error between data yy and the fit f(x)f(x) is the best fit.

The best fit can be obtained by increasing the order of the polynomial and also by splitting the curves into multiple range and then plotting for each range set.

There are different methods to understand the goodness of the curve fit, namely,

1.The sum of squares due to error (SSE), R-square,

2.Adjusted R-square and Root mean squared error (RMSE).

From these quantities, we can evaluate the best fit of the curve.

6].What could be done to improve the cubic fit?
For improving the cubic fit, the splitwise method can be used where the data set in divided into multiple range. More the division, more will be the improvement to the curve.

Conclusion :

By observing the R squared value for each fit, we can say that the Cubic function provides the best fit for the given set of data whereas the linear function provided the worst fit.

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.