|
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 | + |
| 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 |
9 | 33 | 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 |
14 | 41 |
|
15 | 42 |
|
16 |
| -def f(x): |
| 43 | +def f(x: float) -> float: |
17 | 44 | return (x ** 3) - (2 * x) - 5
|
18 | 45 |
|
19 | 46 |
|
20 |
| -def f1(x): |
| 47 | +def f1(x: float) -> float: |
21 | 48 | return 3 * (x ** 2) - 2
|
22 | 49 |
|
23 | 50 |
|
|
0 commit comments