|
| 1 | +import math |
| 2 | + |
| 3 | + |
| 4 | +def fx(x: float, a: float) -> float: |
| 5 | + return math.pow(x, 2) - a |
| 6 | + |
| 7 | + |
| 8 | +def fx_derivative(x: float) -> float: |
| 9 | + return 2 * x |
| 10 | + |
| 11 | + |
| 12 | +def get_initial_point(a: float) -> float: |
| 13 | + start = 2.0 |
| 14 | + |
| 15 | + while start <= a: |
| 16 | + start = math.pow(start, 2) |
| 17 | + |
| 18 | + return start |
| 19 | + |
| 20 | + |
| 21 | +def square_root_iterative( |
| 22 | + a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001 |
| 23 | +) -> float: |
| 24 | + """ |
| 25 | + Sqaure root is aproximated using Newtons method. |
| 26 | + https://en.wikipedia.org/wiki/Newton%27s_method |
| 27 | + |
| 28 | + >>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001 for i in range(0, 500)) |
| 29 | + True |
| 30 | + |
| 31 | + >>> square_root_iterative(-1) |
| 32 | + Traceback (most recent call last): |
| 33 | + ... |
| 34 | + ValueError: math domain error |
| 35 | +
|
| 36 | + >>> square_root_iterative(4) |
| 37 | + 2.0 |
| 38 | +
|
| 39 | + >>> square_root_iterative(3.2) |
| 40 | + 1.788854381999832 |
| 41 | +
|
| 42 | + >>> square_root_iterative(140) |
| 43 | + 11.832159566199232 |
| 44 | + """ |
| 45 | + |
| 46 | + if a < 0: |
| 47 | + raise ValueError("math domain error") |
| 48 | + |
| 49 | + value = get_initial_point(a) |
| 50 | + |
| 51 | + for i in range(max_iter): |
| 52 | + prev_value = value |
| 53 | + value = value - fx(value, a) / fx_derivative(value) |
| 54 | + if abs(prev_value - value) < tolerance: |
| 55 | + return value |
| 56 | + |
| 57 | + return value |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + from doctest import testmod |
| 62 | + |
| 63 | + testmod() |
0 commit comments