torch.trapezoid¶
-
torch.
trapezoid
(y, x=None, *, dx=None, dim=- 1) → Tensor¶ Computes the trapezoidal rule along
dim
. By default the spacing between elements is assumed to be 1, butdx
can be used to specify a different constant spacing, andx
can be used to specify arbitrary spacing alongdim
.Assuming
y
is a one-dimensional tensor with elements , the default computation isWhen
dx
is specified the computation becomeseffectively multiplying the result by
dx
. Whenx
is specified, assumingx
is also a one-dimensional tensor with elements , the computation becomesWhen
y
is two or more dimensions, this computation is performed independently along dimensiondim
. Ifx
is also specified and is one-dimensional, then that dimension defines the spacing for each computation. Ifx
is also specified and is not one-dimensional, then it is broadcast to the shape ofy
and the corresponding sizes are used for each computation. See the examples below for details.Note
The trapezoidal rule is a technique for approximating the definite integral of a function by averaging its left and right Riemann sums. The approximation becomes more accurate as the resolution of the partition increases.
- Parameters
- Keyword Arguments
Examples:
>>> # Computes the trapezoidal rule in 1D, spacing is implicitly 1 >>> y = torch.tensor([1, 5, 10]) >>> torch.trapezoid(y) tensor(10.5) >>> # Computes the same trapezoidal rule directly to verify >>> (1 + 10 + 10) / 2 10.5 >>> # Computes the trapezoidal rule in 1D with constant spacing of 2 >>> # NOTE: the result is the same as before, but multiplied by 2 >>> torch.trapezoid(y, dx=2) 21.0 >>> # Computes the trapezoidal rule in 1D with arbitrary spacing >>> x = torch.tensor([1, 3, 6]) >>> torch.trapezoid(y, x) 28.5 >>> # Computes the same trapezoidal rule directly to verify >>> ((3 - 1) * (1 + 5) + (6 - 3) * (5 + 10)) / 2 28.5 >>> # Computes the trapezoidal rule for each row of a 3x3 matrix >>> y = torch.arange(9).reshape(3, 3) tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> torch.trapezoid(y) tensor([ 2., 8., 14.]) >>> # Computes the trapezoidal rule for each column of the matrix >>> torch.trapezoid(y, dim=0) tensor([ 6., 8., 10.]) >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix >>> # with the same arbitrary spacing >>> y = torch.ones(3, 3) >>> x = torch.tensor([1, 3, 6]) >>> torch.trapezoid(y, x) array([5., 5., 5.]) >>> # Computes the trapezoidal rule for each row of a 3x3 ones matrix >>> # with different arbitrary spacing per row >>> y = torch.ones(3, 3) >>> x = torch.tensor([[1, 2, 3], [1, 3, 5], [1, 4, 7]]) >>> torch.trapezoid(y, x) array([2., 4., 6.])