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 on the Cartesian product of x and y with 1d array of coefficient in Python
To evaluate a 2-D polynomial on the Cartesian product of x and y, use the numpy.polynomial.polynomial.polygrid2d() method in Python. This function returns the values of the two-dimensional polynomial at points in the Cartesian product of x and y arrays.
Syntax
numpy.polynomial.polynomial.polygrid2d(x, y, c)
Parameters
The function accepts three parameters:
- x, y: One-dimensional arrays of coordinates. If x or y is a list or tuple, it is first converted to an ndarray
- c: Array of coefficients ordered so that coefficients for terms of degree i,j are contained in c[i,j]. If c has fewer than two dimensions, ones are implicitly appended to make it 2-D
Example
Let's create a 1D array of coefficients and evaluate a 2-D polynomial ?
import numpy as np
from numpy.polynomial.polynomial import polygrid2d
# Create a 1d array of coefficients
c = np.array([3, 5])
# Display the array
print("Our Array...")
print(c)
# Check the dimensions
print("\nDimensions of our Array...")
print(c.ndim)
# Get the datatype
print("\nDatatype of our Array object...")
print(c.dtype)
# Get the shape
print("\nShape of our Array object...")
print(c.shape)
# Evaluate 2-D polynomial on Cartesian product
print("\nResult...")
print(polygrid2d([1,2], [1,2], c))
The output of the above code is ?
Our Array... [3 5] Dimensions of our Array... 1 Datatype of our Array object... int64 Shape of our Array object... (2,) Result... [21. 34.]
How It Works
The function evaluates the polynomial with coefficients c = [3, 5] at the Cartesian product of points [1,2] and [1,2]. Since c is 1-dimensional, it's treated as a 2-D array with shape (2,1), representing the polynomial 3 + 5*x.
import numpy as np
from numpy.polynomial.polynomial import polygrid2d
# Example with 2D coefficient array
c_2d = np.array([[1, 2], [3, 4]]) # Represents: 1 + 2*y + 3*x + 4*x*y
# Evaluate at specific points
x_vals = [0, 1]
y_vals = [0, 1]
result = polygrid2d(x_vals, y_vals, c_2d)
print("2D polynomial result:")
print(result)
The output shows the evaluation at all combinations ?
2D polynomial result: [[ 1. 3.] [ 4. 10.]]
Conclusion
The polygrid2d() function efficiently evaluates 2-D polynomials on Cartesian products of coordinate arrays. It automatically handles coefficient array dimensions and returns results for all point combinations.
