# [Numpy-discussion] searchsorted

Wed Jun 2 03:16:06 CDT 2004

```
-----Original Message-----
From:	Perry Greenfield [mailto:perry at stsci.edu]
Sent:	Tue 01-Jun-04 19:16
Cc:
Subject:	RE: [Numpy-discussion] searchsorted

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

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

Would that suffice?

Perry

-------------------------------------
Got the idea, the line should be really:

ind = ind - (bins[ind] != val)

You helped a lot.

Thank you very much,