Skip to content

Commit fde31c9

Browse files
billpapscclauss
andauthored
Added Bisection algorithm (TheAlgorithms#1739)
* Create Bisection.py Find root of * Update Bisection.py * Update Bisection.py i changed the given function with one that i could make the doctests. * Rename Bisection.py to bisection.py * Update bisection.py * Update bisection.py * Update bisection.py * Update bisection.py * Update bisection.py Made the changes that were requested * Update bisection.py * Update bisection.py * Add wiki url Co-authored-by: Christian Clauss <[email protected]>
1 parent 1096aa2 commit fde31c9

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

maths/bisection.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Given a function on floating number f(x) and two floating numbers ‘a’ and ‘b’ such that
3+
f(a) * f(b) < 0 and f(x) is continuous in [a, b].
4+
Here f(x) represents algebraic or transcendental equation.
5+
Find root of function in interval [a, b] (Or find a value of x such that f(x) is 0)
6+
7+
https://en.wikipedia.org/wiki/Bisection_method
8+
"""
9+
def equation(x: float) -> float:
10+
"""
11+
>>> equation(5)
12+
-15
13+
>>> equation(0)
14+
10
15+
>>> equation(-5)
16+
-15
17+
>>> equation(0.1)
18+
9.99
19+
>>> equation(-0.1)
20+
9.99
21+
"""
22+
return 10 - x * x
23+
24+
25+
def bisection(a: float, b: float) -> float:
26+
"""
27+
>>> bisection(-2, 5)
28+
3.1611328125
29+
>>> bisection(0, 6)
30+
3.158203125
31+
>>> bisection(2, 3)
32+
Traceback (most recent call last):
33+
...
34+
ValueError: Wrong space!
35+
"""
36+
# Bolzano theory in order to find if there is a root between a and b
37+
if equation(a) * equation(b) >= 0:
38+
raise ValueError("Wrong space!")
39+
40+
c = a
41+
while (b - a) >= 0.01:
42+
# Find middle point
43+
c = (a + b) / 2
44+
# Check if middle point is root
45+
if equation(c) == 0.0:
46+
break
47+
# Decide the side to repeat the steps
48+
if equation(c) * equation(a) < 0:
49+
b = c
50+
else:
51+
a = c
52+
return c
53+
54+
55+
if __name__ == "__main__":
56+
import doctest
57+
58+
doctest.testmod()
59+
60+
print(bisection(-2, 5))
61+
print(bisection(0, 6))

0 commit comments

Comments
 (0)