import mathdef bisection(function, a, b): # finds where the function becomes 0 in [a,b] using bolzanostart = aend = 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 his algorithm can't find the rootprint("couldn't find root in [a,b]")returnelse:mid = (start + end) / 2while abs(start - mid) > 10**-7: # until we achieve precise equals to 10^-7if function(mid) == 0:return midelif function(mid) * function(start) < 0:end = midelse:start = midmid = (start + end) / 2return middef f(x):return math.pow(x, 3) - 2*x - 5if __name__ == "__main__":print(bisection(f, 1, 1000))
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。