Challenge

Curve fitting using Python

Aim: To fit a linear and cubic curve on a given dataset of temperature and specific heat using python

Theory:

Curve fitting is a process of construction of a curve or a mathematical function, that has a best fit to a series of data points. Fitted curve or mathematical function can be used to infer value of function at points where no data is available.

1. Linear curve fitting:

A straight line is fitted with given datapoints to get a best fit.

`y = mx + c`

The objective is to find values of m and c that best fits the data points x and y.

2. Polynomial curve fitting:

A `n^(th)` degree polynomial is fitted with given data point for best fit.

`y = a_1x^n + a_2x^(n-1) + a_3x^(n-2) + ........+ a_(n-1)x + a_n`

The objective is to find values of `a_1,a_2,a_3,..........,a_n` that best fits the data points x nd y.

For one degree polynomial, n=1

`y = a_1x + a_2`

For two degree polynomial, n=2

`y = a_1x^2 + a_2x + a_3`

For cubic polynomial, n=3

'`y = a_1x^3 + a_2x^2 + a_3x + a_4`

Python program:

"""
    Linear and cubic curve fitting
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# Linear polynomial function
def linear(t,m,c):
    return m*t + c

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

# Function to read data file
def read_file():
    temprature = []
    cp = []
    for line in open('data','r'):
        values = line.split(',')
        temprature.append(float(values[0]))
        cp.append(float(values[1]))
    return [temprature, cp]

# Read data from file
temprature, cp = read_file()

# Fit a linear curve
popt_linear, pconv_linear = curve_fit(linear, temprature, cp)
cp_linear = linear(np.array(temprature), *popt_linear)

# Fit a cubic curve
popt_cubic, pconv_cubic = curve_fit(cubic, temprature, cp)
cp_cubic = cubic(np.array(temprature), *popt_cubic)

# plot curves
plt.plot(temprature, cp, 'b')
plt.plot(temprature, cp_linear, 'r')
plt.plot(temprature, cp_cubic, 'g')
plt.legend(['Actual Data','Linear Fit','Cubic Fit'])
plt.xlabel('Temprature[K]')
plt.ylabel('Cp')
plt.show()

For curve fitting curve_fit function is imported from scipy.optimize. Linear and cubic functions are defined for curve fitting. read_file function is defined to read data from file line by line and return data in form of arrays. .append functions add the data to the list. The linear and cubic curve are fitted using curve fit function. Curve fit function return popt and pcov. popt is a 1D array and it gives the optimal coeffiecients of the curve function. For example, for linear curve,it return value of m and c. pcov is a 2D array, it is the estimated covariance of popt. This helps to converge to a specific solution for the curve. It shows how the one coefficients relates with the value of other coefficients or how change in value of one coefficient affects value of other coefficient.It helps choose the optimal solution from different possible results. Without pcov the curve_fit will never converge to an optimal solution.

Using popt for linear and cubic, values of cp are calculated for values of temperature from data file and curve are plotted actual data, linear fit and cubic fit. np.array is used to convert list into numpy array. The curves are plotted using plt.plot function. plt.show() function shows the plot.

Output:

Conclusion:

From the chart it is clear that the cubic curve fits data in much more better way than the linear curve but it is not perfect fit. The cubic curve doesn't perfectly fit the data, it is able to closely approximate it.

In order to perfectly fit the data, the data should be split into small pieces and than it should be fitted.

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.