numpy.polyfit in Python
In this, we are going to see how to fit the data in a polynomial using the polyfit function from standard library numpy in Python.
Suppose, if we have some data then we can use the polyfit() to fit our data in a polynomial.
Polynomial fitting using numpy.polyfit in Python
The simplest polynomial is a line which is a polynomial degree of 1. And that is given by the equation.
And similarly, the quadratic equation which of degree 2. and that is given by the equation
Here the polyfit function will calculate all the coefficients m and c for degree 1. And it calculates a, b and c for degree 2.
Let us consider the example for a simple line.
import matplotlib.pyplot as plt import numpy as np x=np.linspace(-20,20,10) y=2*x+5 plt.plot(x,y,'o')
From the output, we can see that it has plotted as small circles from -20 to 20 as we gave in the plot function.
For now, assume like this our data and have only 10 points.
So, now if we want to fit this data use the polyfit function which is from the numpy package. This can be done as giving the function x and y as our data than fit it into a polynomial degree of 2
We defined polynomial_coeff we give the function which we want to give as x and y our data than fit it into the polynomial of degree 2.
It now calculates the coefficients of degree 2.
array([-6.72547264e-17, 2.00000000e+00, 5.00000000e+00])
The first term is x**2, second term x in the coefficient is 2, and the constant term is 5.
- Now let us define a new x which ranges from the same -20 to 20 and contains 100 points. And we also take the new y for plotting. Let us see the example.
xnew=np.linspace(-20,20,100) ynew=np.poly1d(polynomial_coeff) plt.plot(xnew,ynew(xnew),x,y,'o')
We are taking the evenly spaced elements by using linspace() function which is our xnew. And by using ynew plotting is done with poly1d whereas we can plot the polynomial using this poly1d function in which we need to pass the corresponding coefficient for plotting.
Here the ynew is just a function and we calculate the ynew function at every xnew along with original data.
So from the output, we can observe the data is plotted and fit into a straight line.
- If we want to find the value of the function at any point we can do it by defining the ynew.