torch.cumulative_trapezoid
function cumulative_trapezoid<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(y: Tensor<S, D, Dev>, options?: TrapezoidOptions): Tensor<Shape, D, Dev>function cumulative_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>Computes the cumulative integral along a dimension using the trapezoidal rule.
Like trapezoid, but returns the cumulative integral at each point instead of just the total. At index i, returns the integral from the start to position i. This preserves the integrated dimension (unlike trapezoid which removes it), giving the running integral value at each step. Essential for:
- Signal reconstruction: Getting intermediate integral values, not just the final total
- Cumulative analysis: Tracking integral progression over time or space
- Physics visualization: Showing how position/work accumulates with each sample
- Data exploration: Understanding how values integrate progressively
- Time series integration: Computing cumulative displacement, work, or other quantities
- Output shape: Same as input, with cumulative values along the integrated dimension
- First element is zero: cumulative_trapezoid always starts at 0
- Dimension preserved: Unlike trapezoid, this doesn't reduce dimensionality
- Last element matches trapezoid: Last value of cumulative_trapezoid equals trapezoid result
Parameters
yTensor<S, D, Dev>- The values to integrate (any shape)
optionsTrapezoidOptionsoptional- Optional settings for cumulative_trapezoid
Returns
Tensor<Shape, D, Dev>– Tensor with same shape as input, containing cumulative integral at each positionExamples
// Cumulative integration with uniform spacing
const y = torch.tensor([1, 2, 3, 4]);
torch.cumulative_trapezoid(y);
// [0, 1.5, 4, 7.5] - running sums using trapezoidal rule
// Compare with total trapezoid
const total = torch.trapezoid(y); // 7.5 (just the last element)
const cumul = torch.cumulative_trapezoid(y); // [0, 1.5, 4, 7.5]
// Non-uniform spacing
const x = torch.tensor([0, 1, 3, 6]);
torch.cumulative_trapezoid(y, x);
// [0, 1.5, 7.5, 16.5]
// Visualizing integration progress
const signal = torch.sin(torch.arange(0, 2 * Math.PI, 0.01));
const cumulative = torch.cumulative_trapezoid(signal, { x: 0.01 });
// Shows how the area under sine curve accumulatesSee Also
- PyTorch torch.cumulative_trapezoid()
- trapezoid - Get just the final integral value
- cumsum - Cumulative sum (without trapezoidal approximation)