Numpy-gradient uses forward, backward, and central differences where appropriate.
Input:
x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float)
np.gradient(x) # this uses default distance=1
Output:
array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
For the first item it uses forward (current -> next) difference:
- previous number: none
- current (first) number: 1
- next number: 2
(2 - 1) / 1 = 1.
For the last item it uses backward (previous -> current) difference:
- previous number: 11
- current (last) number: 16
- next number: none
(16 - 11) / 1 = 5.
And, for the items in between, the central difference is applied:
- previous number: 1
- current number: 2
- next number: 4
(4 - 1) / 2 = 1.5
- previous number: 2
- current number: 4
- next number: 7
(7 - 2) / 2 = 2.5
...
and so on:-
(11 - 4) / 2 = 3.5
(16 - 7) / 2 = 4.5
The differences are divided by the sample distance (default=1) for forward and backward differences, but twice the distance for the central difference to obtain appropriate gradients.