Square root approximated using Newton's method. https://en.wikipedia.org/wiki/Newton%27s_method >>> all(abs(square_root_iterative(i) - math.sqrt(i)) <= 1e-14 for i in range(500)) True >>> square_root_iterative(-1) Traceback (most recent call last): ... ValueErr
(
a: float, max_iter: int = 9999, tolerance: float = 1e-14
)
| 19 | |
| 20 | |
| 21 | def square_root_iterative( |
| 22 | a: float, max_iter: int = 9999, tolerance: float = 1e-14 |
| 23 | ) -> float: |
| 24 | """ |
| 25 | Square root approximated using Newton's method. |
| 26 | https://en.wikipedia.org/wiki/Newton%27s_method |
| 27 | |
| 28 | >>> all(abs(square_root_iterative(i) - math.sqrt(i)) <= 1e-14 for i in range(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 _ 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__": |
nothing calls this directly
no test coverage detected