Quickly Find The Index In An Array Closest To Some Value
I have an array of values, t, that is always in increasing order (but not always uniformly spaced). I have another single value, x. I need to find the index in t such that t[inde
Solution 1:
This seems much quicker (for me, Python 3.2-win32, numpy 1.6.0):
from bisect import bisect_left
deff3(t, x):
i = bisect_left(t, x)
if t[i] - x > 0.5:
i-=1return i
Output:
[ 10 11 12 ..., 99997 99998 99999]37854.22200356027378443784437844378543785437854
f1 0.332725
f2 1.387974
f3 0.085864
Solution 2:
np.searchsorted
is binary search (split the array in half each time). So you have to implement it in a way it return the last value smaller than x instead of returning zero.
Look at this algorithm (from here):
defbinary_search(a, x):
lo=0
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
midval = a[mid]
if midval < x:
lo = mid+1elif midval > x:
hi = mid
else:
return mid
return lo-1if lo > 0else0
just replaced the last line (was return -1
). Also changed the arguments.
As the loops are written in Python, it may be slower than the first one... (Not benchmarked)
Solution 3:
Use searchsorted:
t = np.arange(10,100000) # Not always uniform, but in increasing order
x = np.random.uniform(10,100000)
print t.searchsorted(x)
Edit:
Ah yes, I see that's what you do in f1. Maybe f3 below is easier to read than f1.
deff3(t, x):
ind = t.searchsorted(x)
if ind == len(t):
return ind - 1# x > max(t)elif ind == 0:
return0
before = ind-1if x-t[before] < t[ind]-x:
ind -= 1return ind
Post a Comment for "Quickly Find The Index In An Array Closest To Some Value"