Numpy - Polynomials
NumPy provides many functions for working with polynomials, including polynomial fitting, evaluation, and differentiation.
To fit a polynomial to a set of data points, you can use the polyfit
function from NumPy, which takes the data points (specified as two arrays for the independent and dependent variables) and the degree of the polynomial, and returns the coefficients of the polynomial that best fits the data. For example:
import numpy as np
# Fit a polynomial of degree 2 to the data points (0, 0), (1, 1), and (2, 4)
x = np.array([0, 1, 2])
y = np.array([0, 1, 4])
coeffs = np.polyfit(x, y, 2)
print(coeffs) # [ 1. 0. -1.]
The resulting polynomial is 1x^2 + 0x - 1
.
To evaluate a polynomial at a given point, you can use the polyval
function from NumPy, which takes the coefficients of the polynomial and the point, and returns the value of the polynomial at that point. For example:
# Evaluate the polynomial at x = 3
x = 3
y = np.polyval(coeffs, x)
print(y) # 4.0
To differentiate a polynomial, you can use the polyder
function from NumPy, which takes the coefficients of the polynomial and returns the coefficients of the derivative of the polynomial. For example:
# Differentiate the polynomial
deriv_coeffs = np.polyder(coeffs)
print(deriv_coeffs) # [2. 0.]
The resulting polynomial is 2x
.