Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Evaluate a 2-D polynomial at points (x, y) in Python
To evaluate a 2-D polynomial at points (x, y), use the numpy.polynomial.polynomial.polyval2d() method. This function evaluates a two-dimensional polynomial at specified coordinate points and returns the computed values.
Syntax
numpy.polynomial.polynomial.polyval2d(x, y, c)
Parameters
The function accepts three parameters ?
- x, y ? Coordinates where the polynomial is evaluated. Must have the same shape.
-
c ? Array of coefficients where
c[i,j]contains the coefficient for the term of multidegree i,j.
Understanding Coefficient Array
The coefficient array c represents a 2-D polynomial where each element c[i,j] corresponds to the coefficient of x^i * y^j. For a 2×2 coefficient array, the polynomial takes the form ?
# For c = [[c00, c01], [c10, c11]] # Polynomial: c00 + c01*y + c10*x + c11*x*y
Example
import numpy as np
from numpy.polynomial.polynomial import polyval2d
# Create a 2x2 coefficient array
c = np.arange(4).reshape(2, 2)
print("Coefficient Array:")
print(c)
print("\nArray Properties:")
print("Dimensions:", c.ndim)
print("Datatype:", c.dtype)
print("Shape:", c.shape)
# Evaluate polynomial at points (1,1) and (2,2)
x_points = [1, 2]
y_points = [1, 2]
result = polyval2d(x_points, y_points, c)
print("\nEvaluating at points (1,1) and (2,2):")
print("Result:", result)
Coefficient Array: [[0 1] [2 3]] Array Properties: Dimensions: 2 Datatype: int64 Shape: (2, 2) Evaluating at points (1,1) and (2,2): Result: [ 6. 18.]
How It Works
For the coefficient array [[0, 1], [2, 3]], the polynomial is 0 + 1*y + 2*x + 3*x*y. At point (1,1): 0 + 1*1 + 2*1 + 3*1*1 = 6. At point (2,2): 0 + 1*2 + 2*2 + 3*2*2 = 18.
Different Input Shapes
import numpy as np
from numpy.polynomial.polynomial import polyval2d
# Coefficient array for polynomial: 1 + 2*y + 3*x + 4*x*y
c = np.array([[1, 2], [3, 4]])
# Single point evaluation
result1 = polyval2d(1, 2, c)
print("Single point (1,2):", result1)
# Multiple points with arrays
x_vals = np.array([0, 1, 2])
y_vals = np.array([0, 1, 2])
result2 = polyval2d(x_vals, y_vals, c)
print("Multiple points:", result2)
Single point (1,2): 12.0 Multiple points: [ 1. 10. 25.]
Conclusion
The polyval2d() function efficiently evaluates 2-D polynomials at specified coordinate points. The coefficient array structure directly maps to polynomial terms, making it intuitive for mathematical computations involving two-dimensional polynomial expressions.
