Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimal distance between elements in a vector

Tags:

python

numpy

I need the minimal distance between elements of an array.

I did:

numpy.min(numpy.ediff1d(numpy.sort(x)))

Is there a better / more efficient / more elegant / faster way of doing this?

like image 815
Charles Brunet Avatar asked Sep 16 '26 13:09

Charles Brunet


1 Answers

If you are after sheer speed, here are some timings:

In [13]: a = np.random.rand(1000)

In [14]: %timeit np.sort(a)
10000 loops, best of 3: 31.9 us per loop

In [15]: %timeit np.ediff1d(a)
100000 loops, best of 3: 15.2 us per loop

In [16]: %timeit np.diff(a)
100000 loops, best of 3: 7.76 us per loop

In [17]: %timeit np.min(a)
100000 loops, best of 3: 3.19 us per loop

In [18]: %timeit np.unique(a)
10000 loops, best of 3: 53.8 us per loop

The timing of unique was in hopes that it would be comparably fast to sort, and you could break out early without the calls to diff and min if the length of the unique array was shorter than the array itself (as that would mean your answer was 0). But the overhead of unique is more than any gain to be made.

So it seems the only potential improvement I can offer is replacing ediff1d with diff:

In [19]: %timeit np.min(np.diff(np.sort(a)))
10000 loops, best of 3: 47.7 us per loop

In [20]: %timeit np.min(np.ediff1d(np.sort(a)))
10000 loops, best of 3: 57.1 us per loop
like image 58
Jaime Avatar answered Sep 19 '26 05:09

Jaime



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!