Quickly Find the Index in an Array Closest to Some Value

后端 未结 3 1514
日久生厌
日久生厌 2020-12-18 01:34

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

相关标签:
3条回答
  • 2020-12-18 01:44

    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.

    def f3(t, x):
        ind = t.searchsorted(x)
        if ind == len(t):
            return ind - 1 # x > max(t)
        elif ind == 0:
            return 0
        before = ind-1
        if x-t[before] < t[ind]-x:
            ind -= 1
        return ind
    
    0 讨论(0)
  • 2020-12-18 01:53

    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):

    def binary_search(a, x):
        lo=0
        hi = len(a)
        while lo < hi:
            mid = (lo+hi)//2
            midval = a[mid]
            if midval < x:
                lo = mid+1
            elif midval > x: 
                hi = mid
            else:
                return mid
        return lo-1 if lo > 0 else 0
    

    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)

    0 讨论(0)
  • 2020-12-18 02:03

    This seems much quicker (for me, Python 3.2-win32, numpy 1.6.0):

    from bisect import bisect_left
    def f3(t, x):
        i = bisect_left(t, x)
        if t[i] - x > 0.5:
            i-=1
        return i
    

    Output:

    [   10    11    12 ..., 99997 99998 99999]
    37854.22200356027
    37844
    37844
    37844
    37854
    37854
    37854
    f1 0.332725
    f2 1.387974
    f3 0.085864
    
    0 讨论(0)
提交回复
热议问题