【发布时间】:2019-01-14 01:04:46
【问题描述】:
我正在尝试编写一个二分查找函数来查找函数fun 在区间[????????????????????,????????????] 中的根:
这是我所拥有的接近但缺少标记的东西:
def binarySearchIter(fun, start, end, eps=1e-10):
'''
fun: funtion to fund the root
start, end: the starting and ending of the interval
eps: the machine-precision, should be a very small number like 1e-10
return the root of fun between the interval [start, end]
'''
root = (start + end)/2
print(root)
answer=fun(root)
if abs(answer) <= eps:
print(root)
return root
elif answer - eps > 0:
binarySearchIter(fun, start, root, eps=1e-10)
else:
binarySearchIter(fun, root, end, eps=1e-10)
这是我用来测试的函数:
def f(x):
return x ** 2 - 2
当我运行:binarySearchIter(f, -3, 0, eps = 1e-10) 时,我希望得到答案:-1.4142135623842478,但是,root 会收敛到 -3,直到超时。
当我运行binarySearchIter(f, 0, 3, eps = 1e-10) 时,我得到了1.4142135623842478 的正确答案。
我显然遗漏了一些使函数中断的东西,具体取决于它是 (-3, 0) 还是 (3,0)。
感谢您的帮助。
【问题讨论】:
-
二进制和布尔不是同义词
-
你是 100% 正确的,我的错误,感谢 Azat 纠正我。
-
我更喜欢 naxarark 但 azat 可以:)
标签: python python-3.x recursion binary-search