mindspore.ops.diff

mindspore.ops.diff(x, n=1, axis=- 1, prepend=None, append=None)[source]

Computes the n-th discrete difference along a specified axis of a given input x.

The first difference is calculated as \(out[i] = x[i+1] - x[i]\) along the specified axis. To compute higher differences, the function is called recursively using the output from the previous iteration as input.

Note

Zero-shaped Tensor is not supported, a value error is raised if an empty Tensor is encountered. Any dimension of a Tensor is 0, which is considered an empty Tensor. Tensor with shape of \((0,)\), \((1, 2, 0, 4)\) are all empty Tensor.

Parameters
  • x (Tensor) – Input tensor. Full support for signed integers, partial support for floats and complex numbers

  • n (int, optional) – The number of times values are differenced. If zero, the input is returned as-is. Currently only 1 is supported. Default: 1 .

  • axis (int, optional) – The axis along which the difference is taken, default is the last axis. Default: -1 .

  • prepend (Tensor, optional) – Values to prepend to x along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array along all other axis. Otherwise the dimension and shape must match x except along axis. Default: None .

  • append (Tensor, optional) – Values to append to x along axis prior to performing the difference. Scalar values are expanded to arrays with length 1 in the direction of axis and the shape of the input array along all other axis. Otherwise the dimension and shape must match x except along axis. Default: None .

Returns

Tensor, the n-th differences of input. The shape of the output is the same as x except along axis where the size is reduced by n. The type of the output is the same as x.

Raises
Supported Platforms:

Ascend GPU CPU

Examples

>>> from mindspore import Tensor, ops
>>> x = Tensor([1, 3, -1, 0, 4])
>>> out = ops.diff(x)
>>> print(out.asnumpy())
[ 2 -4  1  4]