Project

CURVE FITTING USING PYTHON

OBJECTIVE

  • To write a program in python to fit a linear and cubic polynomial for the Cp data.
  • To plot the temperature against specific Heat (cp).

THEORY ABOUT CURVE FIT

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. Curve fitting can involve either interpolation, where an exact fit to the data is required, or smoothing, in which a "smooth" function is constructed that approximately fits the data. A related topic is regression analysis, which focuses more on questions of statistical inference such as how much uncertainty is present in a curve that is fit to data observed with random errors. Fitted curves can be used as an aid for data visualization, to infer values of a function where no data are available, and to summarize the relationships among two or more variables. Extrapolation refers to the use of a fitted curve beyond the range of the observed data,] and is subject to a degree of uncertainty since it may reflect the method used to construct the curve as much as it reflects the observed data.

The first degree polynomial equation

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.

If the order of the equation is increased to a second degree polynomial, the following results:

This will exactly fit a simple curve to three points.

If the order of the equation is increased to a third degree polynomial, the following is obtained:

This will exactly fit four points.

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

popt:

Array Optimal values for the parameters so that the sum of the squared residuals of f(xdata, *popt) - ydata is minimized

pcov:

2D array estimated covariance of popt. The diagonals provide the variance of the parameter estimate. To compute one standard deviation errors on the parameters use perr = np.sqrt(np.diag(pcov)). How the sigma parameter affects the estimated covariance depends on absolute_sigma argument, as described above.

def linear(x, a, b):

return a * x + b

The arguments to the function should be x, followed by the parameters. We can now call curve fit to find the best-fit parameters using a least-squares fit:

popt, pcov = curve_fit(line, x, y)

The curve_fit function returns two items, which we can popt and pcov. The popt argument are the best-fit parameters for a and b

The reason the values are not exact is because there are only a limited number of random samples, so the best-fit slope is not going to be exactly those used in the definition of y. The pcov variable contains the covariance matrix, which indicates the uncertainties and correlations between parameters. This is mostly useful when the data has uncertainties.

numpy array()

To make a numpy array, you can just use the np.array() function. All you need to do is pass a list to it, and optionally, you can also specify the data type of the data.

NumPy array is a central data structure of the numpy library. The library’s name is short for “Numeric Python” or “Numerical Python

PROCEDURE

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

  • Initially we import these three libraries to plot the curve, numerical calculations and curve fittings.
  • Then create two functions one for linear curve fit and other one is for cubic curve fit.
  • Then we are going to define one more function to read the data from we saved in same folder and we create two empty array for temperature and cp.
  • After that using line,split(‘,’) we will split the data and assign values using append command for temperature cp.
  • Then we are going to return the value to empty arrays of temperature and cp.
  • After that temp and cp is read the data and using curve fit function to perform curve fitting using the actual data.
  • Popt and pvoc is the output of the function curve fit.
  • Then call the function of linear to calculate the values of linear function and store in the array and np.array() is used to create numpy array and temperature is passed as the data of the array.
  • And using the same procedure we find the values for cubic function.
  • After that using the plot command we create the plot for temperature against curve fittings.

PROGRAM

#program for curve fit in python
#by Sallavoddin

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

#Linear curve fit function
def flinear(x,a,b):
	return a*x+b

#Cubic curve fit function
def fcubic(x,a,b,c,d):
	return a*pow(x,3)+b*pow(x,2)+c*x+d


#read the 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
#program for linear curve fit
temperature,cp=read_file()
popt,pcov=curve_fit(flinear, temperature,cp)
fit_cp=flinear(np.array(temperature), *popt)

#program for cubic curve fit
temperature,cp=read_file()
popt,pcov=curve_fit(fcubic, temperature,cp)
fit_cp1=fcubic(np.array(temperature), *popt)


#plot for the actual data vs Linear curve fit
plt.figure()
plt.plot(temperature,cp,linewidth=3,color='blue')
plt.plot(temperature,fit_cp,linewidth=3,color='red')
plt.xlabel('Temperature[k]')
plt.ylabel('Specific Heat[k/kgk]')
plt.title('Actual data vs Linear curve fit')
plt.legend(['Actual data','Linear fit'])

plt.show()

#plot for the actual data vs Cubic curve fit
plt.plot(temperature,cp,linewidth=3,color='blue')
plt.plot(temperature,fit_cp1,linewidth=3,color='yellow')
plt.xlabel('Temperature[k]')
plt.ylabel('Specific Heat[k/kgk]')
plt.title('Actual data vs Cubic curve fit')
plt.legend(['Actual data','cubic fit'])

plt.show()

OUTPUT

For linear curve fit

For cubic curve fit

CONCLUSION

  • In the actual data vs linear curve fit plot we can see that there is lot of difference between the actual data and linear curve fit data.
  • In the actual data vs Cubic curve fit plot we can see that the actual data and linear curve fit data is closer compare to the linear curve fit data.
  • If we will go to the higher polynomial data we will get the more accurate data, but if we go higher order, then it takes more time to calculate and it increase complexity of the problem.

REFFERENCES

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.