لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.

# Python Data Science NumPy ufunc Differences

A discrete difference means subtracting two successive elements.

E.g. for [1, 2, 3, 4, 5], the discrete difference would be [2-1, 3-2, 4-3, 5-4] = [1, 1, 1, 1]

We use the diff() function to find the discrete difference.

Example 1: Compute discrete difference of the following array.

Code

import numpy as np

arr = np.array([20, 25, 35, 5])

newarr = np.diff(arr)

print(newarr)

the output will be

[ 5 10 -30]

Returns: [5 10 -30] because 25-20=5, 35-25=10, and 5-35=-30.

We can perform this operation repeatedly by giving parameter n. E.g. for [1, 2, 3], the discrete difference with n = 2 would be [2-1, 3-2] = [1, 1].

Since n=2, we will do it once more, with the new result: [1-1] = [0]

Example 2: Compute discrete difference of the following array twice.

Code

import numpy as np

arr = np.array([2, 5, 7, 9])
newarr = np.diff(arr, n=2)

print(newarr)

the output will be

[-1 0]

Returns: [-1 0] because: 5-2=3, 7-5=2, and 9-7=2 AND 2-3=-1 and 2-2=0.
Note: NumPy ufunc Universal function or ufuncs is a function which operates on ndarrays in an element by element fashion and supports array broadcasting, type casting, and many other standard features.