Evaluate a polynomial at points x with multidimensioanl array of roots in Python

To evaluate a polynomial specified by its roots at points x, use the polynomial.polyvalfromroots() method in Python NumPy. This function takes the roots of a polynomial and evaluates the resulting polynomial at given points.

Syntax

numpy.polynomial.polynomial.polyvalfromroots(x, r, tensor=True)

Parameters

The function accepts three parameters ?

  • x ? Points at which to evaluate the polynomial. Can be a scalar, list, tuple, or ndarray
  • r ? Array of roots. For multidimensional arrays, the first index represents the root index
  • tensor ? Boolean flag controlling evaluation behavior for multidimensional roots (default: True)

Understanding Multidimensional Roots

When r is multidimensional, the first index is the root index, while remaining indices enumerate multiple polynomials. In a 2D case, each column represents roots of a different polynomial.

Example

from numpy.polynomial.polynomial import polyvalfromroots
import numpy as np

# Create an array of multidimensional roots
roots = np.arange(-2, 2).reshape(2, 2)

# Display the array
print("Roots Array:")
print(roots)

# Check array properties
print("\nDimensions:", roots.ndim)
print("Datatype:", roots.dtype)
print("Shape:", roots.shape)

# Evaluate polynomial at x = 1
result = polyvalfromroots(1, roots)
print("\nPolynomial evaluation at x = 1:")
print(result)
Roots Array:
[[-2 -1]
 [ 0  1]]

Dimensions: 2
Datatype: int64
Shape: (2, 2)

Polynomial evaluation at x = 1:
[3. 0.]

How It Works

The function constructs polynomials from the given roots and evaluates them. For the roots array [[-2, -1], [0, 1]] ?

  • First polynomial has roots [-2, 0], giving polynomial (x+2)(x-0) = x² + 2x
  • Second polynomial has roots [-1, 1], giving polynomial (x+1)(x-1) = x² - 1

At x = 1: First polynomial = 1 + 2 = 3, Second polynomial = 1 - 1 = 0

Multiple Evaluation Points

from numpy.polynomial.polynomial import polyvalfromroots
import numpy as np

roots = np.array([[-2, -1], [0, 1]])
x_values = [0, 1, 2]

result = polyvalfromroots(x_values, roots)
print("Evaluation at multiple points:")
print("x values:", x_values)
print("Results:")
print(result)
Evaluation at multiple points:
x values: [0, 1, 2]
Results:
[[0. 3. 8.]
 [-1. 0. 3.]]

Conclusion

The polyvalfromroots() function efficiently evaluates polynomials defined by their roots at specified points. It handles multidimensional root arrays, making it useful for evaluating multiple polynomials simultaneously.

---
Updated on: 2026-03-26T19:38:02+05:30

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements