MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / square_root_iterative

Function square_root_iterative

maths/numerical_analysis/square_root.py:21–57  ·  view source on GitHub ↗

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
)

Source from the content-addressed store, hash-verified

19
20
21def square_root_iterative(
22 a: float, max_iter: int = 9999, tolerance: float = 1e-14
23) -> float:
24 """
25 Square root approximated using Newton&#x27;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
60if __name__ == "__main__":

Callers

nothing calls this directly

Calls 3

get_initial_pointFunction · 0.85
fxFunction · 0.85
fx_derivativeFunction · 0.85

Tested by

no test coverage detected