Skip to content

Instantly share code, notes, and snippets.

@tcely
Last active May 3, 2025 04:24
Show Gist options
  • Save tcely/759fd28e45a3d81961b0897e5af037a5 to your computer and use it in GitHub Desktop.
Save tcely/759fd28e45a3d81961b0897e5af037a5 to your computer and use it in GitHub Desktop.
Python square root functions
def newtons_sqrt(i, /, *, precision=1e-10):
loops = 0
x = (1+i) // 2
d = i
n_x = 0
print(f'{precision=}', flush=True)
while loops < x and abs(d) > precision:
loops += 1
print(f'{loops=} abs(d) = {abs(d)}: {d=}', flush=True)
n_x = x - (x*x - i)/(2*x)
print(f' {n_x=} {x=} {i=}', flush=True)
print(f' x*x={x*x} 2*x={2*x}', flush=True)
print(
f' (x*x-i)={x*x-i} '
f'(x*x-i)/(2*x)={(x*x - i)/(2*x)} ',
flush=True,
)
d = n_x - x
x = n_x
print(f' {d=} {x=}', flush=True)
return (n_x, int(n_x), loops,)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment