Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.diff with parameter n=2 produces strange result

Tags:

python

numpy

I'm having a hard time understanding the behaviour of np.diff when n>1

The documentation gives the following example :

x = np.array([1, 2, 4, 7, 0])
np.diff(x)
array([ 1,  2,  3, -7])
np.diff(x, n=2)
array([  1,   1, -10])

It seems from the first example that we are substracting each number by the previous one (x[i+1]-x[i]) and all results make sense.

The second time the function is called, with n=2, it seems that we're doing x[i+2]-x[i+1]-x[i] and the two first numbers (1 and 1) in the resulting array make sense but I am surprised the last number is not -11 (0 -7 -4) but -10.

Looking in the documentation I found this explaination

The first difference is given by out[i] = a[i+1] - a[i] along the given axis, higher differences are calculated by using diff recursively.

I fail to understand this 'recursively' so I'd be glad if someone had a clearer explanation !

like image 911
Gato Marbré Avatar asked Dec 06 '25 11:12

Gato Marbré


1 Answers

np.diff(x, n=2) is the same as np.diff(np.diff(x)) (that's what "recursively" means in this case).

like image 122
Riccardo Bucco Avatar answered Dec 09 '25 01:12

Riccardo Bucco



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!