Project

Curve fitting in python

Theory - 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 smoothin, 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 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.

Procedure: We begin by writing a function to read the data file provided to us.

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]

This function reads the values from the files and stores them as temperature and cp values.

After that, we write two more functions, linear and cubic which will represent cp as a function of temperature. Our aim is to represent cp as a function of temperature choosing the best possible representation so that we get a good fit.

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

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

Now, we will use inbuilt curve_fit command in scipy.optmize module to get values of coefficients of polynomial equations. NOTE: p_cov returns the covariance of the constants. Covariance measures the degree to which two variables are linearly associated.

temp,cp = read_file()

# linear curve fitting
popt_l,pcov_l = curve_fit(linear,temp,cp)
cp_l = linear(array(temp),*popt_l)

#cubic curve fitting
popt_c,pcov_c = curve_fit(cubic,temp,cp)
cp_c = cubic(array(temp),*popt_c)

We have used terms cp_l for linear function nd cp_c for cubic function. \'*\' sign is used to pass multiple values while writings argument of a function.

Now for checking the goodness of it i.e. how close our polynomial function is to the actual data, we hve various methods. In this problem, R-squared method has been used. More closer the value of R-squared is to 1, better are our results.

Outputs

\"\"

The graph clearly shows that cubic polynomial does a better job at curve fitting than linear polynomial. We can get even better results by using different polynomial equations for different ranges of temperature.

\"\"

Complete code:

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

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]

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

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


temp,cp = read_file()

# linear curve fitting
popt_l,pcov_l = curve_fit(linear,temp,cp)
cp_l = linear(array(temp),*popt_l)

#cubic curve fitting
popt_c,pcov_c = curve_fit(cubic,temp,cp)
cp_c = cubic(array(temp),*popt_c)

plt.figure()
plt.plot(temp,cp,label= \'actual data\')
plt.plot(temp,cp_l,linewidth = 1,label = \'linearly fit data\')
plt.plot(temp,cp_c,linewidth =2,label = \'cubic fit data\')
plt.legend()
plt.show()

#goodness of fit for linear curve
ss_res = sum((cp - cp_l) ** 2)

# total sum of squares
ss_tot = sum((cp - mean(cp)) ** 2)

# r-squared
r2 = 1 - (ss_res / ss_tot)
print(\'The value of r-squared for linear fit is\',round(r2,4)  )

#goodness of fit for cubic curve
ss_res_c = sum((cp - cp_c) ** 2)

# total sum of squares
ss_tot_c = sum((cp - mean(cp)) ** 2)

# r-squared
r2_c = 1 - (ss_res_c / ss_tot_c)
print(\'The value of r-squared for cubic fit is\',round(r2_c,4))
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.