nlcpy.diff
- nlcpy.diff(a, n=1, axis=- 1, prepend=nlcpy._NoValue, append=nlcpy._NoValue)
Calculates the n-th discrete difference along the given axis.
The first difference is given by
out[i] = a[i+1] - a[i]
along the given axis, higher differences are calculated by using diff recursively.- Parameters
- aarray_like
Input array
- nint, optional
The number of times values are differenced. If zero, the input is returned as-is.
- axisint, optional
The axis along which the difference is taken, default is the last axis.
- prepend, appendarray_like, optional
Values to prepend or append to a 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 in along all other axes. Otherwise the dimension and shape must match a except along axis.
- Returns
- diffndarray
The n-th differences. The shape of the output is the same as a except along axis where the dimension is smaller by n. The type of the output is the same as the type of the difference between any two elements of a.
See also
cumsum
Returns the cumulative sum of the elements along a given axis.
Note
Type is preserved for boolean arrays, so the result will contain False when consecutive elements are the same and True when they differ.
For unsigned integer arrays, the results will also be unsigned. This should not be surprising, as the result is consistent with calculating the difference directly:
>>> import nlcpy as vp >>> a = vp.array([1, 0], dtype='uint32') >>> vp.diff(a) array([4294967295], dtype=uint32) >>> vp.array([0], dtype='uint32') - vp.array([1], dtype='uint32') array([4294967295], dtype=uint32)
if this is not desirable, then the array should be cast to a larger integer type first:
>>> b = a.astype(vp.int64) >>> vp.diff(b) array([-1])
Examples
>>> x = vp.array([1, 2, 4, 7, 0]) >>> vp.diff(x) array([ 1, 2, 3, -7]) >>> vp.diff(x, n=2) array([ 1, 1, -10]) >>> x = vp.array([[1, 3, 6, 10], [0, 5, 6, 8]]) >>> vp.diff(x) array([[2, 3, 4], [5, 1, 2]]) >>> vp.diff(x, axis=0) array([[-1, 2, 0, -2]])