3
3
# Newton's Method - https://en.wikipedia.org/wiki/Newton%27s_method
4
4
from typing import Callable
5
5
6
+ RealFunc = Callable [[float ], float ] # type alias for a real -> real function
7
+
6
8
7
9
# 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 :
13
11
"""
14
12
>>> newton(lambda x: x ** 3 - 2 * x - 5, lambda x: 3 * x ** 2 - 2, 3)
15
13
2.0945514815423474
@@ -27,17 +25,19 @@ def newton(
27
25
>>> newton(math.cos, lambda x: -math.sin(x), 0)
28
26
Traceback (most recent call last):
29
27
...
30
- ZeroDivisionError: float division by zero, could not find root
28
+ ZeroDivisionError: Could not find root
31
29
"""
32
30
prev_guess : float = starting_int
33
31
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" )
41
41
42
42
43
43
def f (x : float ) -> float :
0 commit comments