Curve Fitting Using Python
Curve Fitting
Introduction
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 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 = f(x), where f(x) can be of any degree i.e.,
`y = a_0 + a_1 x + a_2 x^2 + a_3 x^3 + ... + a_n x^n`
A thing to be noticed is that there are n+1 coefficients to the equation.
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.
Structure of the Program
- A function 'func()' is defined to return the value of the polynomial.
- 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.
- The function 'readfile()' is called and assigned to two variables 'cp' and 'temp'.
- 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.
- The function 'curve_fit' returns the coefficients in descending order of power of the polynomial which is stored as 'potp'. And it also returns a covariance matrix 'pcov' whose diagonal elements are the variance values of the coefficients.
- These set of values are used for curve fitting. The function 'func()' is called with 'np.array(temp)' and '*popt' as inputs. Since the function func() requires three individual coefficient values, '*' is used with 'popt'. This gives the individual values of the array 'popt'. 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.
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(t,a,b,c):
return a*pow(t,2)+b*t+c
def func1(t,a,b,c,d):
return a*pow(t,3)+b*pow(t,2)+c*t+d
def read_file():
temp = []
cp = []
for line in open('data','r'):
values = line.split(',')
temp.append(float(values[0]))
cp.append(float(values[1]))
return[temp,cp]
# Main Program
temp,cp = read_file()
popt,pcov = curve_fit(func,temp,cp)
fit_cp = func(np.array(temp),*popt)
plt.figure(1)
plt.plot(temp,cp,color="blue",Linewidth=3)
plt.plot(temp,fit_cp,color="red",linewidth=3)
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('Cp')
plt.title('Quadratic Fit')
plt.show()
# Cubic fit
temp1,cp1 = read_file()
popt1,pcov1 = curve_fit(func1,temp1,cp1)
fit_cp1 = func1(np.array(temp1),*popt1)
plt.figure(2)
plt.plot(temp1,cp1,color="blue",Linewidth=3)
plt.plot(temp1,fit_cp1,color="red",linewidth=3)
plt.legend(['Actual Data','Curve Fit'])
plt.xlabel('Temperature[K]')
plt.ylabel('Cp')
plt.title('Cubic Fit')
plt.show()
OUTPUT
The accuracy is average in the quadratic fit but the accuracy has been improved in the Cubic fit.
The goodness of fit can be improved by increasing the order of the polynomial.


