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 smoothing, in which a \"smooth\" function is constructed that approximately fits the data. A related topic is a 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:

  • a,b,c,d are variables are used to predict the value of y for each X term.

1.what is POP and Pcov ?

  • pcov is a 2d array with the estimated covariance of the parameters in popt. It can be used to calculate the the standard deviation errors of popt.
  • \"popt\" gives optimized curve for the given function, its gives best-fit parameter.
  • The \"popt\" is the co-efficient of values of a,b,c,d.
  • 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 paramters for a and b:

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

  • This command is used to convert the all temperature into the numpy function , this command is used for some of the math operation cannot be done on list.

3. What does the * in *popt mean?

Note that there is a way to simplify the call to the function with the best-fit parameters, which is:

    • line(x, *popt)
      The * notation will expand a list of values into the arguments of the function. This is useful if your function has more than one or two parameters. Secondary and third array also we used for cubic curve fit.

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

MAIN PROGRAM:

Case 1: Linear Curve Fit.

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

#curve fir function (linear)

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

# Reading file

def read_file():
	temperature =[]
	cp = []

	for line in open(\'data\',\'r\'):
		value = line.split(\',\')
		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)
fit_cp = func(np.array(temperature),*popt)
print(popt)

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(cp)\')
plt.savefig(\'Linear curve fit\')
plt.show()

case 2:cubic polynomial.

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

#curve fir function (Cubic)

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

# Reading file

def read_file():
	temperature =[]
	cp = []

	for line in open(\'data\',\'r\'):
		value = line.split(\',\')
		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)
fit_cp = func(np.array(temperature),*popt)
print(popt)

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(cp)\')
plt.savefig(\'Linear curve fit\')
plt.show()

PROCEDURE:

  • Importing the required files for program running like \"matplotlib\",\"numpy\",\"scipy for curve fit\".
  • Defining the Linear order equation(a*t+b) for the running linear polynomial .
  • For reading file we need to define the function for read_file(), its read the data in which we stroed in same folder.
  • Creating a empty array for for the temperature and specific heat ,cp used to stored the values .
  • using for loop command in which it used for line to open (\'data\',\'r\'), which is used to read the content of the data in which we read.
  • using command value =line.split(\',\'), which is used to split the data as we required.
  • Data we used to string value used convert with float and append command used to store the value in empty array we created.
  • By using the \"curve_fit\" function fpr linear order, we get an output for temperature and specific heat cp.
  • After getting the output as an popt , the output value of fit_cp we pass the value of temperature in data as numpy array so that it can be executed.
  • We need to plot the output data using the plt.plot of temperature and specific heat cp & temperature with fit_cp.
  • After finishing the case 1, for case 2 we need to use the cubic order of equation a*pow(t,3)+b*pow(t,2)+c*t+d
  • And rest of the procedure are same as the above method.

OUTPUT: PLOTS FOR LINEAR, CUBIC.

1. Curve fitting with a linear polynomial

2.curve fitting with a cubic polynomial

Results are good are Bad:

  • From above comparing two cases of graphs shows that linear function curve is not accurate with actual data and curve not matched.
  • while using the cubic equation and its output data similary match with data given so, hence we can declare that second equation results is \"GOOD\".
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.