Skip to content

Commit 473072b

Browse files
spamegg1cclauss
andauthored
added type hints and doctests to arithmetic_analysis/newton_method.py (#2259)
* added type hints and doctests to arithmetic_analysis/newton_method.py Continuing #2128 Also changed some variable names, made them more descriptive. * 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 * added type hints and doctests to arithmetic_analysis/newton_method.py improved exception handling * Update newton_method.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 9cda130 commit 473072b

File tree

1 file changed

+36
-11
lines changed

1 file changed

+36
-11
lines changed

Diff for: arithmetic_analysis/newton_method.py

+36-11
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,48 @@
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+
RealFunc = Callable[[float], float] # type alias for a real -> real function
7+
8+
9+
# function is the f(x) and derivative is the f'(x)
10+
def newton(function: RealFunc, derivative: RealFunc, starting_int: int,) -> float:
11+
"""
12+
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
13+
2.0945514815423474
14+
>>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -2)
15+
1.0
16+
>>> newton(lambda x: x ** 3 - 1, lambda x: 3 * x ** 2, -4)
17+
1.0000000000000102
18+
>>> import math
19+
>>> newton(math.sin, math.cos, 1)
20+
0.0
21+
>>> newton(math.sin, math.cos, 2)
22+
3.141592653589793
23+
>>> newton(math.cos, lambda x: -math.sin(x), 2)
24+
1.5707963267948966
25+
>>> newton(math.cos, lambda x: -math.sin(x), 0)
26+
Traceback (most recent call last):
27+
...
28+
ZeroDivisionError: Could not find root
29+
"""
30+
prev_guess float(starting_int)
931
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
32+
try:
33+
next_guess = prev_guess - function(prev_guess) / derivative(prev_guess)
34+
except ZeroDivisionError:
35+
raise ZeroDivisionError("Could not find root")
36+
if abs(prev_guess - next_guess) < 10 ** -5:
37+
return next_guess
38+
prev_guess = next_guess
1439

1540

16-
def f(x):
41+
def f(x: float) -> float:
1742
return (x ** 3) - (2 * x) - 5
1843

1944

20-
def f1(x):
45+
def f1(x: float) -> float:
2146
return 3 * (x ** 2) - 2
2247

2348

0 commit comments

Comments
 (0)