python写二分法_Python中的二分法

对于函数,只需将函数名作为参数传递。我已经将函数名改为root11,并将其作为对分的第一个参数。在

为了伯爵。。。你应该能在网上查到这个。只需像学习for语句之前那样计算迭代次数。返回这个和最后的答案。在

请注意,我删除了您的检查以获得准确的答案:无论如何,您将在下一次迭代中找到它。在def root11(x):

return(x**2 - 11)

def bisection_method(f, a, b, tol):

if f(a)*f(b) > 0:

#end function, no root.

print("No root found.")

else:

iter = 0

while (b - a)/2.0 > tol:

midpoint = (a + b)/2.0

if f(a)*f(midpoint) < 0: # Increasing but below 0 case

b = midpoint

else:

a = midpoint

iter += 1

return(midpoint, iter)

answer, iterations = bisection_method(root11, -1, 5, 0.0001)

print("Answer:", answer, "\nfound in", iterations, "iterations")

import math

answer, iterations = bisection_method(math.cos, 0, 2, 0.0001)

print("Answer:", answer, "\nfound in", iterations, "iterations")

输出:

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值