Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.gradient() seems to produce erroneous boundary values (using first differences)

Tags:

python

numpy

There seems to be a problem with the function numpy.gradient() (numpy 1.9.0) regarding how it computes the boundary (start and end) values (which I know it does using first differences, while central values are computed using central differences). Consider for instance the following example:

import numpy as np
arr = np.array([1, 2, 4])
arrgrad = np.gradient(arr)

I would here expect arrgrad to obtain the values

[ 1.   1.5  2. ]

i.e.

arrgrad[0] = (2-1)/1 = 1
arrgrad[1] = (4-1)/2 = 1.5  
arrgrad[2] = (4-2)/1 = 2

but I get the result

[ 0.5  1.5  2.5]

The behaviour of numpy.gradient() from version 1.8.1 (obtained from https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/function_base.py) seems to produce the correct result, however.

Is the erroneous behaviour described above the a result of a bug? (I'm using Python 3.4.2, 64 bit.)

like image 614
andreasdr Avatar asked Dec 08 '25 19:12

andreasdr


1 Answers

Apparently the way gradients are calculated was changed between 1.8.1 and 1.9.0 by 332d628, so that boundary elements are now calculated using a second-order accurate approximation as well, whereas previously they were only first-order accurate.

However, the documentation on the numpy website does not include 1.9.0 docs, only up to 1.8.1, so to see the proper documentation you can use np.source(np.gradient) or print(np.gradient.__doc__).

like image 189
pseudocubic Avatar answered Dec 10 '25 09:12

pseudocubic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!