Ka Wa Yip
Ka Wa Yip

Reputation: 2983

How to interpret numpy.gradient?

In the first example of the documentation http://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html

x = np.array([1, 2, 4, 7, 11, 16], dtype=np.float)
np.gradient(x)
array([ 1. ,  1.5,  2.5,  3.5,  4.5,  5. ])

Isn't the output should be:

array([ 1. ,  1.,  2.,  3.,  4.,  5. ])

???

Upvotes: 6

Views: 4148

Answers (2)

swatchai
swatchai

Reputation: 18782

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.

Upvotes: 15

oschoudhury
oschoudhury

Reputation: 1146

What you expect as output is what you will get when running np.diff, but then one element shorter:

np.diff(arr)
>>> array([ 1.,  2.,  3.,  4.,  5.])

np.gradient looks takes the i'th element and looks at the average between the differences for the (i+1)'th vs. i'th element and the (i-1)'th vs. i'th element. For the edge values it only can use one point. So value number two comes 1.5 comes from averaging (2-1) and (4-2).

Upvotes: 5

Related Questions