Skip to content

Commit f26b8b2

Browse files
committed
added type hints and doctests to arithmetic_analysis/newton_method.py
Continuing #2128 Also changed some variable names, made them more descriptive.
1 parent 9cda130 commit f26b8b2

File tree

1 file changed

+38
-11
lines changed

1 file changed

+38
-11
lines changed

Diff for: arithmetic_analysis/newton_method.py

+38-11
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,50 @@
11
"""Newton's Method."""
22

33
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
4-
5-
6-
# function is the f(x) and function1 is the f'(x)
7-
def newton(function, function1, startingInt):
8-
x_n = startingInt
4+
from typing import Callable
5+
6+
7+
# 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:
13+
"""
14+
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
15+
2.0945514815423474
16+
>>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -2)
17+
1.0
18+
>>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -4)
19+
1.0000000000000102
20+
>>> import math
21+
>>> newton(math.sin, math.cos, 1)
22+
0.0
23+
>>> newton(math.sin, math.cos, 2)
24+
3.141592653589793
25+
>>> newton(math.cos, lambda x: -math.sin(x), 2)
26+
1.5707963267948966
27+
>>> newton(math.cos, lambda x: -math.sin(x), 0)
28+
Traceback (most recent call last):
29+
...
30+
ZeroDivisionError: float division by zero, could not find root
31+
"""
32+
prev_guess: float = starting_int
933
while True:
10-
x_n1 = x_n - function(x_n) / function1(x_n)
11-
if abs(x_n - x_n1) < 10 ** -5:
12-
return x_n1
13-
x_n = x_n1
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
1441

1542

16-
def f(x):
43+
def f(x: float) -> float:
1744
return (x ** 3) - (2 * x) - 5
1845

1946

20-
def f1(x):
47+
def f1(x: float) -> float:
2148
return 3 * (x ** 2) - 2
2249

2350

0 commit comments

Comments
 (0)