From: Nadav H. <na...@vi...> - 2004-06-02 10:15:47
|
-----Original Message----- From: Perry Greenfield [mailto:pe...@st...] Sent: Tue 01-Jun-04 19:16 To: Nadav Horesh; numpy-discussion Cc:=09 Subject: RE: [Numpy-discussion] searchsorted Nadav Horesh writes > I am currently working on a simulation that makes a heavy use of=20 > searchsorted. But it does not precisely fit to what I need --- if a=20 > value v is between p and q searchsorted returns the index of q, while = > what I need is the index of p. >=20 > Currently my solution is to turn to floating points numbers: >=20 > = =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >=20 > 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 * >=20 > bins =3D array((0,10,20,30)) > val =3D array((10, 15)) > searchsorted(bins, val) > array([1, 2]) # I really would like to get array([1, 1]) >=20 > # Here is the trick: >=20 > fb =3D bins - 0.1 > fb > array([ -0.1, 9.9, 19.9, 29.9]) >=20 > searchsorted(fb, val) - 1 > array([1, 1]) # That's it! >=20 This is only approximate, right? If val =3D array([9.95, 15]) you will get the wrong answer won't you? > = =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >=20 > My questions are: >=20 > 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=3DBool)] > Any comments? >=20 > Nadav. >=20 To get the latter, you could so something like ind =3D searchsorted(bins, val) neq_mask =3D bins[ind]-val ind[neq_mask] -=3D 1. # well, you need to handle where ind =3D 0 and # is not equal as well Would that suffice? Perry ------------------------------------- Got the idea, the line should be really: ind =3D ind - (bins[ind] !=3D val) You helped a lot. Thank you very much, Nadav. |