Python numpy.polyfit() Method with Example

Python | numpy.polyfit(): Learn about the numpy.polyfit() method, its usages and example. By Pranit Sharma Last updated : December 25, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Python numpy.polyfit() Method

The numpy.polyfit() method is used for finding the best fitting curve to a given set of points by minimizing the sum of squares, which means that this function helps us by finding the least square polynomial fit.

A mathematical expression generally composed of more than one variable where the degree of the variable is usually a whole number is said to be a polynomial.

If there is a polynomial of degree k to points (x,y), it fits a polynomial p(x) = p[0] * x**k + ... + p[k]. It returns a vector of coefficients p that minimizes the squared error in the order k, k-1, … 0.

Syntax

numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)

Parameter(s)

  • x: x-coordinates of sample points.
  • Y: y coordinates of sample points.
  • deg: degree of polynomial fit
  • rcond: relative condition number of the fit.

Return Value

Polynomial coefficients, highest power first. If y was 2-D, the coefficients for k-th data set are in p[:,k]. [source]

Let us understand with the help of an example,

Python code to demonstrate the example of numpy.polyfit() method

import numpy as np

# Creating points for x
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])

# Creating points for y
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])

# Display x and y
print("X and Y sample points:\n",x,"\n",y,"\n")

# Using numpy.polyfit
res = np.polyfit(x,y,3)

# Display result
print("Result:\n",res)

Output

Example: numpy.polyfit() Method with Example

Python NumPy Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.