0
点赞
收藏
分享

微信扫一扫

Python:实现bisection二等分算法(附完整源码)

静悠 2022-07-30 阅读 48


Python:实现bisection二等分算法

def equation(x: float) -> float:

return 10 - x * x


def bisection(a: float, b: float) -> float:

# Bolzano theory in order to find if there is a root between a and b
if equation(a) * equation(b) >= 0:
raise ValueError("Wrong space!")

c = a
while (b - a) >= 0.01:
# Find middle point
c = (a + b) / 2
# Check if middle point is root
if equation(c) == 0.0:
break
# Decide the side to repeat the steps
if equation(c) * equation(a) < 0:
b = c
else:
a = c
return c


if __name__ == "__main__":
import doctest

doctest.testmod()

print(bisection(-2, 5))
print(bisection(0, 6))


举报

相关推荐

0 条评论