Evaluate a 2D Legendre series on the Cartesian product of x and y in Python

To evaluate a 2D Legendre series on the Cartesian product of x and y, use the polynomial.legendre.leggrid2d() method in NumPy. This method evaluates a two-dimensional Legendre series at points formed by the Cartesian product of x and y coordinates.

The method returns values of the two-dimensional Legendre series at specified grid points. If the coefficient array c has fewer than two dimensions, ones are implicitly appended to make it 2D. The result shape will be c.shape[2:] + x.shape + y.shape.

Syntax

numpy.polynomial.legendre.leggrid2d(x, y, c)

Parameters

x, y: The two-dimensional series is evaluated at points in the Cartesian product of x and y. Lists or tuples are converted to ndarrays, while scalars are treated as single points.

c: Array of coefficients where c[i,j] contains the coefficient for the term of multi-degree i,j. Higher dimensions enumerate multiple coefficient sets.

Example

Let's evaluate a 2D Legendre series using a coefficient matrix ?

import numpy as np
from numpy.polynomial import legendre as L

# Create a 2D array of coefficients
c = np.arange(4).reshape(2,2)

# Display the coefficient array
print("Coefficient Array:")
print(c)

# Check array properties
print("\nArray Dimensions:", c.ndim)
print("Array Datatype:", c.dtype)
print("Array Shape:", c.shape)

# Evaluate 2D Legendre series on Cartesian product
result = L.leggrid2d([1,2], [1,2], c)
print("\nResult:")
print(result)
Coefficient Array:
[[0 1]
 [2 3]]

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

Result:
[[ 6. 10.]
 [11. 18.]]

How It Works

The function evaluates the 2D Legendre series defined by:

f(x,y) = ??? c[i,j] * L?(x) * L?(y)

Where L? and L? are Legendre polynomials of degrees i and j respectively. For our coefficient matrix [[0,1],[2,3]], this becomes:

f(x,y) = 0*L?(x)*L?(y) + 1*L?(x)*L?(y) + 2*L?(x)*L?(y) + 3*L?(x)*L?(y)

Different Input Examples

You can use different x and y coordinate arrays ?

import numpy as np
from numpy.polynomial import legendre as L

# Same coefficient matrix
c = np.array([[0, 1], [2, 3]])

# Example 1: Single point evaluation
x_point, y_point = 0.5, 1.5
result_point = L.leggrid2d([x_point], [y_point], c)
print(f"At point ({x_point}, {y_point}):", result_point[0][0])

# Example 2: Different grid sizes
x_vals = [0, 1, 2]
y_vals = [0, 1]
result_grid = L.leggrid2d(x_vals, y_vals, c)
print(f"\nGrid evaluation shape: {result_grid.shape}")
print("Grid results:")
print(result_grid)
At point (0.5, 1.5): 4.0

Grid evaluation shape: (2, 3)
Grid results:
[[ 2.  1.  4.]
 [ 2.  1.  4.]]

Conclusion

The leggrid2d() function efficiently evaluates 2D Legendre series on coordinate grids. It's particularly useful for polynomial surface fitting and numerical analysis involving Legendre basis functions.

Updated on: 2026-03-26T21:06:34+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements