MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / bisection

Function bisection

maths/numerical_analysis/bisection_2.py:27–54  ·  view source on GitHub ↗

>>> bisection(-2, 5) 3.1611328125 >>> bisection(0, 6) 3.158203125 >>> bisection(2, 3) Traceback (most recent call last): ... ValueError: Wrong space!

(a: float, b: float)

Source from the content-addressed store, hash-verified

25
26
27def bisection(a: float, b: float) -> float:
28 """
29 >>> bisection(-2, 5)
30 3.1611328125
31 >>> bisection(0, 6)
32 3.158203125
33 >>> bisection(2, 3)
34 Traceback (most recent call last):
35 ...
36 ValueError: Wrong space!
37 """
38 # Bolzano theory in order to find if there is a root between a and b
39 if equation(a) * equation(b) >= 0:
40 raise ValueError("Wrong space!")
41
42 c = a
43 while (b - a) >= 0.01:
44 # Find middle point
45 c = (a + b) / 2
46 # Check if middle point is root
47 if equation(c) == 0.0:
48 break
49 # Decide the side to repeat the steps
50 if equation(c) * equation(a) < 0:
51 b = c
52 else:
53 a = c
54 return c
55
56
57if __name__ == "__main__":

Callers 1

bisection_2.pyFile · 0.70

Calls 1

equationFunction · 0.85

Tested by

no test coverage detected