Evaluate a 3D Legendre series on the Cartesian product of x, y and z with 2d array of coefficient in Python

To evaluate a 3D Legendre series on the Cartesian product of x, y and z, use the polynomial.legendre.leggrid3d() method in Python NumPy. The method returns the values of the three-dimensional Legendre series at points in the Cartesian product of x, y, and z. If the coefficient array has fewer than three dimensions, ones are implicitly appended to its shape to make it 3D.

Syntax

numpy.polynomial.legendre.leggrid3d(x, y, z, c)

Parameters

The method accepts the following parameters ?

  • x, y, z ? The three-dimensional series is evaluated at points in the Cartesian product of x, y, and z. If any parameter is a list or tuple, it is converted to an ndarray.
  • c ? Array of coefficients ordered so that the coefficient of the term of multi-degree i,j,k is contained in c[i,j,k]. For 2D arrays, the third dimension is implicitly added.

Example

Let's create a 2D coefficient array and evaluate the 3D Legendre series ?

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 array
print("Coefficient Array:")
print(c)
print(f"Shape: {c.shape}")
print(f"Dimensions: {c.ndim}")
print(f"Datatype: {c.dtype}")

# Evaluate 3D Legendre series on Cartesian product
x = [1, 2]
y = [1, 2] 
z = [1, 2]

result = L.leggrid3d(x, y, z, c)
print(f"\nResult shape: {result.shape}")
print("Result:")
print(result)
Coefficient Array:
[[0 1]
 [2 3]]
Shape: (2, 2)
Dimensions: 2
Datatype: int64

Result shape: (2, 2, 2)
Result:
[[[17. 28.]
  [28. 46.]]

 [[28. 46.]
  [46. 76.]]]

How It Works

The method evaluates the Legendre series for each combination of (x, y, z) coordinates. Since we provided 2D coefficients, NumPy automatically extends it to 3D by adding a dimension. The resulting array has shape (2, 2, 2) corresponding to all combinations of the input coordinates.

Different Input Shapes

You can use different array shapes for x, y, and z coordinates ?

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

# Create coefficient array
c = np.array([[1, 2], [3, 4]])

# Use different coordinate arrays
x = [0, 1]
y = [0]  # Single y value
z = [1, 2, 3]  # Three z values

result = L.leggrid3d(x, y, z, c)
print(f"Input shapes - x: {np.array(x).shape}, y: {np.array(y).shape}, z: {np.array(z).shape}")
print(f"Result shape: {result.shape}")
print("Result:")
print(result)
Input shapes - x: (2,), y: (1,), z: (3,)
Result shape: (1, 3, 2)
Result:
[[[8. 12.]
  [8. 12.]
  [8. 12.]]]

Conclusion

The leggrid3d() method efficiently evaluates 3D Legendre series on Cartesian product coordinates. It automatically handles dimension expansion for 2D coefficient arrays and returns results with shape determined by the input coordinate arrays.

Updated on: 2026-03-26T20:47:26+05:30

237 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements