Skip to content

Commit 4ad625d

Browse files
committed
Added type hints and doctests to arithmetic_analysis/newton_method.py
added a type alias for Callable[[float], float] and cleaned up the exception handling
1 parent f26b8b2 commit 4ad625d

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

Diff for: arithmetic_analysis/newton_method.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@
33
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
44
from typing import Callable
55

6+
RealFunc = Callable[[float], float] # type alias for a real -> real function
7+
68

79
# function is the f(x) and derivative is the f'(x)
8-
def newton(
9-
function: Callable[[float], float],
10-
derivative: Callable[[float], float],
11-
starting_int: int,
12-
) -> float:
10+
def newton(function: RealFunc, derivative: RealFunc, starting_int: int,) -> float:
1311
"""
1412
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
1513
2.0945514815423474
@@ -27,17 +25,19 @@ def newton(
2725
>>> newton(math.cos, lambda x: -math.sin(x), 0)
2826
Traceback (most recent call last):
2927
...
30-
ZeroDivisionError: float division by zero, could not find root
28+
ZeroDivisionError: Could not find root
3129
"""
3230
prev_guess: float = starting_int
3331
while True:
34-
if derivative(prev_guess) == 0:
35-
raise ZeroDivisionError("float division by zero, could not find root")
36-
37-
next_guess: float = prev_guess - function(prev_guess) / derivative(prev_guess)
38-
if abs(prev_guess - next_guess) < 10 ** -5:
39-
return next_guess
40-
prev_guess = next_guess
32+
try:
33+
next_guess: float = prev_guess - function(prev_guess) / derivative(
34+
prev_guess
35+
)
36+
if abs(prev_guess - next_guess) < 10 ** -5:
37+
return next_guess
38+
prev_guess = next_guess
39+
except ZeroDivisionError:
40+
raise ZeroDivisionError("Could not find root")
4141

4242

4343
def f(x: float) -> float:

0 commit comments

Comments
 (0)