|
1 | 1 | """Newton's Method.""" |
2 | 2 |
|
3 | 3 | # 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) |
9 | 31 | 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 |
14 | 39 |
|
15 | 40 |
|
16 | | -def f(x): |
| 41 | +def f(x: float) -> float: |
17 | 42 | return (x ** 3) - (2 * x) - 5 |
18 | 43 |
|
19 | 44 |
|
20 | | -def f1(x): |
| 45 | +def f1(x: float) -> float: |
21 | 46 | return 3 * (x ** 2) - 2 |
22 | 47 |
|
23 | 48 |
|
|
0 commit comments