numpy.polyfit with examples

Here, In this tutorial, we will learn about numpy.polyfit() in Python with the help of some examples. numpy.polyfit() is a function in Python that is defined to find the least square polynomial fit. It simply means finding the best-fitting curve by minimizing the sum of squares to the set of points given. So read the tutorial very carefully to clear all your doubts regarding numpy.polyfit and enjoy coding in Python.

This method takes inputs from the user, named X, Y, and polynomial degrees. In this case, X and Y represent the values we want to fit on the 2 axes.

Syntax of numpy.polyfit()

numpy.polyfit(xydeg)
x and y are the variables, where our data is stored.
deg, is the abbreviation for a degree, it indicates the degree of the polynomial function.

np.polyfit to find the coefficients of variables of a polynomial

The polyfit function in the numpy package, fits a polynomial function to our data, in the program below, we can create a polynomial using the polyfit function and also trace the coefficients of the different variables of that polynomial.

# import the numpy package
import numpy as np
# define the varialbles
x=[1,2,3,4,5,6,7,8]
y=[2.1,44.2,56,12.43,54,33.21,98,7.6]
# find the coefficients of the polynomial with degree 2
coefficient=np.polyfit(x,y,deg=2)
# print the coefficients
print(coefficient)
Output:
[ -2.31952381  24.21738095 -11.38785714]
coefficient of x^2= -2.31952381
coefficient of x= 24.21738095
constant= -11.38785714

Create a polynomial using np.polyfit

We can create polynomials using the np.polyfit function. We require poly1d function to create the polynomial of the given data.

# import the numpy package
import numpy as np
# define the data 
x=[1,2,3,4,5,6,7,8]
y=[2.1,44.2,56,12.43,54,33.21,98,7.6]
# coefficients of the variables of the polynomial
coefficient=np.polyfit(x,y,deg=2)
# complete polynomial
polynomial=np.poly1d(coefficient)
print(polynomial)
Output:
       2
-2.32 x + 24.22 x - 11.39

Create a plot using polyfit:

We can also use the polyfit function to create plots. We will be using the Matplotlib library to make a graphical plot.

# import matplotlib
import matplotlib.pyplot as plt
# import the numpy package
import numpy as np
# define the data 
x=[1,2,3,4,5,6,7,8]
y=[2.1,44.2,56,12.43,54,33.21,98,7.6]
# coefficients of the variables of the polynomial
coefficient=np.polyfit(x,y,deg=2)
# complete polynomial
polynomial=np.poly1d(coefficient)
# create a scattered plot
plt.scatter(x,y,color='red')
plt.show()
Output:

numpy.polyfit

Leave a Reply

Your email address will not be published. Required fields are marked *