Challenge

Week 5 - Curve fitting

TITLE: CURVE FITTING

OBJECTIVE: To write a python code for curve fiiting of a mathematical expression.

Answers to the questions

1. popt is an array containing the value of the coefficients "a,b,c,d"

2. The pcov variable contains the covariance matrix, which indicates the uncertainties and correlations between parameters.

3. we are using this star(*)in *popt, to store all the values of coefficients in popt array.

4.Here the results are good as the curve fits with the orginal.

5.Here I use higher order polynomial i.e `at^3 + bt^2 +ct + d` in order to get perfect fit.

Curve fitting is the process of constructing a curve, or mathematical functions, which possess the closest proximity to the real series of data. By curve fitting, we can mathematically construct the functional relationship between the observed dataset and parameter values, etc. It is highly effective in the mathematical modeling of some natural processes.

Assuming data points (x1,y1) , (x2,y2) , (x3,y3) , ... (xn,yn) and assume the best fit for these set of points will be y = f(x), the criterion under which the equation of the curve will be the best fit possible is as follows,

CODE:

import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit 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('data','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) print(popt) print(pcov) fit_cp = func(np.array(temperature),*popt) plt.plot(temperature,cp) plt.plot(temperature,fit_cp) plt.legend(['actual data','curve_fit']) plt.xlabel('Temperature') plt.ylabel('cp') plt.show()

RESULT:

CONCLUSION: Here I use higher order polynomial to get perfect fit for the curve.

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.