Project

curve fit-python

popt: An array of values containing the paramters that would minimize the sum of squares of the residuals.

pcov: An array containing the estimated covariance of popt

np.array(temperature) : it coverts the list of temperature values into numpy array so as to be able to perform mathematical operations like \'pow\'.

*in*popt: it refers to the values stored in the array popt.

LINEAR POLYNOMIAL FOR Cp DATA:

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

# Curve fitting function
def func(t, a, b):
	return a*t + b

def read_file():
	temperature = []
	cp = []
	for line in open(\'curve_fit.txt\',\'r\'):
		values = line.split(\',\')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))
	return [temperature, cp]

temperature, cp = read_file()
popt, pcov = curve_fit(func, temperature, cp)
fit_cp = func(np.array(temperature), *popt)

plt.plot(temperature, cp, color=\"black\", linewidth=3)
plt.plot(temperature, fit_cp, color=\"red\", linewidth=3)
plt.legend([\'Actual Data\',\'Curve Fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'CP\')

plt.show()

CUBIC POLYNOMIAL FOR Cp DATA:

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

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

def read_file():
	temperature = []
	cp = []
	for line in open(\'curve_fit.txt\',\'r\'):
		values = line.split(\',\')
		temperature.append(float(values[0]))
		cp.append(float(values[1]))
	return [temperature, cp]

temperature, cp = read_file()
popt, pcov = curve_fit(func, temperature, cp)
fit_cp = func(np.array(temperature), *popt)

plt.plot(temperature, cp, color=\"blue\", linewidth=3)
plt.plot(temperature, fit_cp, color=\"brown\", linewidth=3)
plt.legend([\'Actual Data\',\'Curve Fit\'])
plt.xlabel(\'Temperature\')
plt.ylabel(\'CP\')

plt.show()

From the plots, it is identified that the cubic polynimial gives a better fit that linear polynomial and the curve isn\'t good because it doesn\'t tally completely with the original data set.

To make the curve much accurate, higher degree polynomimals can be used.

A curve fit of 4th degree polynomial is shown

output:

To make the curv fit perfect,

the degree of the polynomial should be increased. higher degrees indicate higher accuracy but also consume a lot of time to execute as programs. so here, a degree of 4 is optimum.

this can aso be done by performing regression analysis using least square method or polynomial regression.

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.