[Numpy-discussion] searchsorted

Nadav Horesh nadavh at visionsense.com
Tue Jun 1 06:32:05 CDT 2004


I am currently working on a simulation that makes a heavy use of 
searchsorted. But it does not precisely fit to what I need --- if a 
value v is between p and q  searchsorted returns the index of q, while 
what I need is the index of p.

Currently my solution is to turn to floating points numbers:

======================================

Python 2.3.4 (#1, May 31 2004, 09:13:03)
[GCC 3.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from numarray import *

bins = array((0,10,20,30))
val = array((10, 15))
searchsorted(bins, val)
array([1, 2])  # I really would like to get array([1, 1])

# Here is the trick:

fb = bins - 0.1
fb
array([ -0.1,   9.9,  19.9,  29.9])

searchsorted(fb, val) - 1
array([1, 1])    #  That's  it!

============================================

My questions are:

   1. Is there a more elegant solution?
   2. I am thinking of letting "searchsorted" return a second boolean
      array which has the value True for every exact match:
       >>> searchsorted(bins, val)
       >>> [array([1, 2]), array([1, 0], type=Bool)]
      Any comments?

Nadav.




More information about the Numpy-discussion mailing list