[Numpy-discussion] searchsorted

Perry Greenfield perry at stsci.edu
Tue Jun 1 09:17:00 CDT 2004


Nadav Horesh writes

> 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!
> 
This is only approximate, right? If val = array([9.95, 15])
you will get the wrong answer won't you?

> ============================================
> 
> 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.
> 
To get the latter, you could so something like

ind = searchsorted(bins, val)
neq_mask = bins[ind]-val
ind[neq_mask] -= 1. # well, you need to handle where ind = 0 and
                    #  is not equal as well

Would that suffice?

Perry




More information about the Numpy-discussion mailing list