A discrete difference is obtained by subtracting successive elements in an array. For instance, the discrete difference of [1, 2, 3, 4] is [1, 1, 1]. This can be calculated using the diff() function.
Calculate the discrete difference for the following array:
import numpy as np arr = np.array([10, 15, 25, 5]) newarr = np.diff(arr) print(newarr) |
We can repeat the discrete difference operation by specifying a parameter nn. For example, with the array [1, 2, 3, 4] and n=2n=2, the first discrete difference is [1, 1, 1]. Applying the operation again gives [0, 0].
Calculate the discrete difference of the following array two times:
import numpy as np arr = np.array([10, 15, 25, 5]) newarr = np.diff(arr, n=2) print(newarr) |