Hong-Phuc Bui
2024-04-29 931d213d4395c6d0ef93f30fe606da8ee3baa6d2
python-grundlage/sqrt-newton.py
old mode 100644 new mode 100755
@@ -1,10 +1,12 @@
#! /usr/bin/env python
import sys
from typing import Final
n = float(sys.argv[1])
EPSILON = sys.float_info.epsilon
EPSILON: Final[float] = sys.float_info.epsilon
t = n
while abs(t - n/t) > (EPSILON*t):
    t = (n / t + t) / 2
x = n                                         # !$x_0 = n$!
while abs(x - (q := n / x)) > (EPSILON * x):  # !$\left|\frac{x^2-n}{x^2}\right| > \varepsilon $!
    x = (x + q) / 2.0                         # !$x_{i+1} = \frac{1}{2}(x_i + \frac{n}{x_i})$!
print(f"sqrt({n}) ~= {t}")
print(f"sqrt({n}) ~ {x}")