我希望能够找到函数输出第一个True
的值。目前我的搜索功能可以正常工作,但我认为仍然有一点效率问题。请问是否有更好的二分搜索方法?以下是我简化后的代码。
guess = 2
limits = [2, 2**35] #The search area
while True:
if myFunction(guess) == False:
limits[0] = max(limits[0], guess) #Limit the search area
guess *= 2
else:
limits[1] = min(limits[1], guess) #Limit the search area
guess = int((limits[0] + limits[1])/2) #The guess is the midpoint of the search area
if myFunction(guess) == True and myFunction(guess-1) == False:
return guess
myFunction
对于小于某个数N
的值返回 False,并对大于或等于N
的所有值返回 True。目标是找到N
。因此可以使用二分查找来找到N
,同时调用myFunction
不超过 35 次。但next
将进行线性搜索,并且可能最多调用myFunction
340亿次。 - user3386109guess *= 2
- 这可能会将guess
值移出搜索域。 - kfx