且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

快速找到最接近某个值的数组中的索引

更新时间:2022-11-14 08:12:39

这似乎要快得多(对我来说,Python 3.2-win32,numpy 1.6.0):

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