Quickly Find the Index in an Array Closest to Some Value

后端 未结 3 1516
日久生厌
日久生厌 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: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)

提交回复
热议问题