torch.trapezoid
function trapezoid<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(y: Tensor<S, D, Dev>, options?: TrapezoidOptions): Tensor<Shape, D, Dev>function trapezoid<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(y: Tensor<S, D, Dev>, x: Tensor | number, dim: number, options?: TrapezoidOptions): Tensor<Shape, D, Dev>Integrates values along a dimension using the trapezoidal rule.
Approximates the area under a curve by treating the curve as a series of line segments (trapezoids) and summing their areas. Works with both uniform and non-uniform sample spacing. Essential for:
- Numerical integration: Computing definite integrals from sampled function values
- Signal processing: Integrating continuous signals from discrete samples
- Physics simulations: Computing work, displacement, or other cumulative quantities
- Data analysis: Estimating areas under curves (AUC for ROC curves, etc.)
- Time series analysis: Integrating quantities that vary over time
The trapezoidal rule is a simple and accurate numerical integration method when sample spacing is small. For uniform spacing, pass dx as a scalar. For non-uniform spacing, pass x coordinates as a tensor.
- Dimension reduced: The integrated dimension is removed from output (or becomes 1 if keepdim=true)
- Default spacing: dx=1 if neither x nor dx specified
- Non-uniform spacing: x must have same length as y along the integrated dimension
Parameters
yTensor<S, D, Dev>- The values to integrate (any shape)
optionsTrapezoidOptionsoptional
Returns
Examples
// Uniform spacing: integrate y = [1, 2, 3, 4] with dx=1
const y = torch.tensor([1, 2, 3, 4]);
torch.trapezoid(y); // 7.5 = (1+2)*1/2 + (2+3)*1/2 + (3+4)*1/2
// Uniform spacing with larger steps
torch.trapezoid(y, 0.5); // 3.75 = same calculation but with dx=0.5
// Non-uniform spacing with explicit x coordinates
const x = torch.tensor([0, 1, 3, 6]);
torch.trapezoid(y, x); // Uses actual x spacing: (1+2)*1/2 + (2+3)*2/2 + (3+4)*3/2
// 2D integration (integrate each row)
const y2d = torch.tensor([[1, 2, 3], [4, 5, 6]]);
torch.trapezoid(y2d, 1, -1); // [3, 12]See Also
- PyTorch torch.trapezoid()
- cumulative_trapezoid - Get cumulative integral instead of total
- sum - Sum all elements (different from integration)