Challenge

Week 5 - Curve fitting

AIM: - Write a program to performing a curve fit.

1.What does popt and pcov mean?

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

3. What does the * in *popt mean?

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

5. What needs to be done in order to make the curve fit perfect?

Objective

Curve fitting: -

Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. Curve fitting is involving 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. It is highly effective in the mathematical modelling of some natural processes. 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.

Fitting lines and polynomial functions to data points: -

The first degree polynominal equation

y = a*x + b

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:

y = a*x^2 + b*x + c

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:

y = a*x^3 + b*x^2 + c*x + d

This will exactly fit four points.

popt and pcov mean

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

Other word it store the value of co-efficient of given polynomial

pcov : 2d array The 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.

which is to say: use p_sigma = np.sqrt(np.diag(pcov))

np.array(temperature)

It is converted the temperature data in an array of shape 3200, shape can be obtain by using print(np.array(temperature).shape).

* in *popt mean

Python provide a functionality if we want to pass arbitray number of argument.

* means, it definition of the function will function will accept the argument supplied in the function that are not identified as a list.

In order to make the curve fit perfect

PERFECT FIT:

The perfect fit is achieved when the geometric distances from the given points to the fitting curve are zero. This means that the curve fits perfectly on the points. To get a perfect fit we can increase to a order of the polynomials, this method increases the accuracy and reduces errors.

BEST Fit :

The best fit is achieved when the geometric distances from the given points to the fitting curve are minimized, in the least squares sense. Finding the best fit reduces to the minimization of the objective function where denotes the fitting curve.

Upon finding a curve which satisfies the data points there are 4 quantities which help us measure the goodness of fit criteria or how well the equation is a representing the data points.

Programming: -

#Curve fit using a python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

#Curve fit function (to define a function)
def func(t,a,b,c):
return a*pow(t,2) + b*t + c

#Reading thermodynamic data file
# Here file contain two coloum temperature and specific heat and presure are constant

def read_file():
temperature = []
cp = []
for line in open('data','r'): #'r' is read the file (read the each line)
value = line.split(',')
# below procedure use to convert spring to float
#store the value in temperature in temperature array
temperature.append(float(value[0]))
cp.append(float(value[1]))
return[temperature,cp]

#Main program

temperature,cp = read_file()
popt,pcov = curve_fit(func,temperature,cp) # it define the three co-efficient
fit_cp = func(np.array(temperature),*popt) # to recalculate curve fit value
plt.plot(temperature,cp,color = "green",linewidth = 3)
plt.plot(temperature,fit_cp,color = "blue",linewidth = 3)
plt.legend(['Actual data','curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('cp')
plt.show()

Explaination of programming:

1) Import the numpy as np in a core library

2)Import matplotlib.pyplot as plt to make python work as matlab.matplot.pyplot is collection.

3)from scipy.optimize import curve_fit is fuction from a package.

4) Define a function func.

t,a and b are passing the function argument.

5)return a*pow(t,2) + b*t + c is return the output of the function.

6)def read_file(): is use to define function to read the data.

7)To define the empty array like a temperature = [] and cp = []

8)for line in open('data','r'): is use to open the data file to read the data contain.

9)value = line.split(',') use to split the all the line.

10)temperature.append(float(value[0]))
cp.append(float(value[1]))

store the all value of temperature form first coloum and cp value in second coloum.

11)return[temperature,cp] is use to return array

12)popt,pcov = curve_fit(func,temperature,cp) # it define the three co-efficient
fit_cp = func(np.array(temperature),*popt) # to recalculate curve fit value

#using the curve_fit function to perform curve fitting the actual data

cp containing the actual data passed as a argument to the function of curve _fit.

popt is optimum value of co-efficient

pcov is 2d array contain the estimated covariance of the parameter.

13)plt.plot

It is use to plot the graph

14)legend anf label command use to add the legend and label the name in graph.

15)plt.show() is use to show the plot

Result Plot

Conclusion:

From the above code we see that as order of the polynomial gets higer the better fit obtained.

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.