Skip to content

Commit bd74f20

Browse files
authored
added type hints and doctests to arithmetic_analysis/bisection.py (#2241)
* added type hints and doctests to arithmetic_analysis/bisection.py continuing in line with #2128 * modified arithmetic_analysis/bisection.py Put back print statement at the end, replaced algorithm's print statement with an exception. * modified arithmetic_analysis/bisection.py Removed unnecessary type import "Optional" * modified arithmetic_analysis/bisection.py Replaced generic Exception with ValueError. * modified arithmetic_analysis/bisection.py fixed doctests
1 parent dfb4ce4 commit bd74f20

File tree

1 file changed

+31
-14
lines changed

1 file changed

+31
-14
lines changed

Diff for: arithmetic_analysis/bisection.py

+31-14
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,38 @@
1-
import math
1+
from typing import Callable
22

33

4-
def bisection(
5-
function, a, b
6-
): # finds where the function becomes 0 in [a,b] using bolzano
7-
8-
start = a
9-
end = b
4+
def bisection(function: Callable[[float], float], a: float, b: float) -> float:
5+
"""
6+
finds where function becomes 0 in [a,b] using bolzano
7+
>>> bisection(lambda x: x ** 3 - 1, -5, 5)
8+
1.0000000149011612
9+
>>> bisection(lambda x: x ** 3 - 1, 2, 1000)
10+
Traceback (most recent call last):
11+
...
12+
ValueError: could not find root in given interval.
13+
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
14+
1.0
15+
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
16+
3.0
17+
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
18+
Traceback (most recent call last):
19+
...
20+
ValueError: could not find root in given interval.
21+
"""
22+
start: float = a
23+
end: float = b
1024
if function(a) == 0: # one of the a or b is a root for the function
1125
return a
1226
elif function(b) == 0:
1327
return b
1428
elif (
1529
function(a) * function(b) > 0
1630
): # if none of these are root and they are both positive or negative,
17-
# then his algorithm can't find the root
18-
print("couldn't find root in [a,b]")
19-
return
31+
# then this algorithm can't find the root
32+
raise ValueError("could not find root in given interval.")
2033
else:
21-
mid = start + (end - start) / 2.0
22-
while abs(start - mid) > 10 ** -7: # until we achieve precise equals to 10^-7
34+
mid: float = start + (end - start) / 2.0
35+
while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7
2336
if function(mid) == 0:
2437
return mid
2538
elif function(mid) * function(start) < 0:
@@ -30,9 +43,13 @@ def bisection(
3043
return mid
3144

3245

33-
def f(x):
34-
return math.pow(x, 3) - 2 * x - 5
46+
def f(x: float) -> float:
47+
return x ** 3 - 2 * x - 5
3548

3649

3750
if __name__ == "__main__":
3851
print(bisection(f, 1, 1000))
52+
53+
import doctest
54+
55+
doctest.testmod()

0 commit comments

Comments
 (0)