Challenge

Week 5 - Curve fitting

curve fitting:

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 smoothing7 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 interference 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

Most commonly; a curve fit is done in the form y = where f(x) can be of any degree

y=a0+a1x+a2x^2+a3x^3+----+anx^n

i.e. A thing to be noticed is that there are n+l coefficients to the equation

The first-degree polynomial equation

y=ax+b

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:

y=ax^2+bx+c

This will exactly fit a simple curve to three points

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

y=ax^3+bx^2+cx+d

This will exactly fit a simple curve to four points

1) What does popt and pcov mean ?

Answer: popt is an array which consists of optimum values of the coefficients of the function(linear,quadratic,cubic etc.) so that the error is minimum between the actual data and the curve fit. pcov is an array which consists of the estimated Covariance of popt. Covariance is the measure of how changes in one variable is associated with changes in the second variable.

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

Answer: numpy is imported as np in my program.

np.array(), is used to create an array using the numpy library.

np.array(temperature), creates an array for the temperature values in the data file.

3)What does the * in *popt mean?

Answer: In Python, the * provides the functionality when we must pass arbitrary number of arguements, the * used will accept the arguements supplied in the function that are not identified as a list, it is intialized to a tuple.

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

answer:Increasing the degree of polynomial function used for curve fitting ,will make the curve fit perfect

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

#linear polynomial:
def func1(t,a,b):
    return a*t+b

#quadratic polynomial
def func2(t,a,b,c):
    return a*pow(t,2)+b*t+c

#cubic polynomial
def func3(t,a,b,c,d):
    return a*pow(t,3)+b*pow(t,2)+c*t+d

#reading 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]

#linear fit 
temperature,cp=read_file()
popt,pocv=curve_fit(func1,temperature,cp)
fit_cp=func1(np.array(temperature),*popt)

plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cp,color='red',linewidth=3)
plt.legend(['actual data','curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('cp')
plt.show()

#quadratic fit 
temperature,cp=read_file()
popt,pocv=curve_fit(func2,temperature,cp)
fit_cp=func2(np.array(temperature),*popt)

plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cp,color='red',linewidth=3)
plt.legend(['actual data','curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('cp')
plt.show()

#cubic fit
temperature,cp=read_file()
popt,pocv=curve_fit(func3,temperature,cp)
fit_cp=func3(np.array(temperature),*popt)

plt.plot(temperature,cp,color='blue',linewidth=3)
plt.plot(temperature,fit_cp,color='red',linewidth=3)
plt.legend(['actual data','curve fit'])
plt.xlabel('temperature[k]')
plt.ylabel('cp')
plt.show()

OUTPUTS:-

LINEAR FIT

QUADRATIC FIT

CUBIC FIT

Hence ,the result of cubic polynomial is good whereas that of linear polynomial is bad

EXPLANATION OF CODE:

1) A function 'func() is defined to return the value of the polynomial

2)The file containing the data is copied to two variables namely cp' and 'temp' in the Python program in a defined function 'readfile()' using open' function.

3)The function 'readfile()' is called and assigned to two variables 'cp' and temp'.

4). A curve is to fit for 'cp' and 'temp' values, so a function 'curve_fit' is called and assigned to two new variables. The inputs for the function are (func(),temp,cp) in the same order.

5)The term 'np.array(temp)' creates an array object whose each value is taken at a time by the function 'func()' along with the coefficients.

6)From This, we can conclude that as we increase the order of polynomial value of R square increases and so the Best Fit can be achieved.

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.