# How do I interpret numpy.gradient?

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

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

```

The output should not be:

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

```

???

+3

source to share

What you expect as output is what you get on startup `np.diff`

, but then one item is shorter:

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

```

`np.gradient`

looks at the i'th element and looks at the mean between the differences for the `(i+1)`

'th vs. `i`

'th and `(i-1)`

' th vs. `i`

'th element. For edge values, it can only use one point. So the number two comes `1.5`

from averaging `(2-1)`

and `(4-2)`

.

+3

source

The Numpy gradient uses, where appropriate `forward`

, `backward`

and `central`

differences.

Input data:

``````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 element, it uses the forward difference:
(2 - 1) / 1 = 1.

For the last element, it uses the reverse difference:
(16 - 11) / 1 = 5.

And, for the elements in between, the central difference applies:
(4 - 1) / 2 = 1.5
(7 - 2) / 2 = 2.5
(11-4) / 2 = 3.5
(16-7) / 2 = 4.5

Differences are divided by the fetch distance for forward jumps and backward (default = 1), but twice the distance for the center difference to get the corresponding gradients.

+6

source

All Articles