同步操作将从 编程语言算法集/Python 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
from typing import Callabledef bisection(function: Callable[[float], float], a: float, b: float) -> float:"""finds where function becomes 0 in [a,b] using bolzano>>> bisection(lambda x: x ** 3 - 1, -5, 5)1.0000000149011612>>> bisection(lambda x: x ** 3 - 1, 2, 1000)Traceback (most recent call last):...ValueError: could not find root in given interval.>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)1.0>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)3.0>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)Traceback (most recent call last):...ValueError: could not find root in given interval."""start: float = aend: float = bif function(a) == 0: # one of the a or b is a root for the functionreturn aelif function(b) == 0:return belif (function(a) * function(b) > 0): # if none of these are root and they are both positive or negative,# then this algorithm can't find the rootraise ValueError("could not find root in given interval.")else:mid: float = start + (end - start) / 2.0while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7if function(mid) == 0:return midelif function(mid) * function(start) < 0:end = midelse:start = midmid = start + (end - start) / 2.0return middef f(x: float) -> float:return x ** 3 - 2 * x - 5if __name__ == "__main__":print(bisection(f, 1, 1000))import doctestdoctest.testmod()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。