Skip to content

Instantly share code, notes, and snippets.

@malfet
Last active March 31, 2023 01:50
Show Gist options
  • Save malfet/fd741b465e24973ad1d7234b018b9986 to your computer and use it in GitHub Desktop.
Save malfet/fd741b465e24973ad1d7234b018b9986 to your computer and use it in GitHub Desktop.
Spigot algorithm for computing digits of square root
#!/usr/bin/env python3
# Adapted from https://rosettacode.org/wiki/Square_root_by_hand
def next_digit(val, k):
for d in range(1, 11):
if val < d * (k + d):
return d - 1
raise RuntimeError("Impossible")
def compute_sqrt(val=2, num_char=500):
j = int(val**.5)
k, d = j, j
rc=""
for n in range(num_char):
rc=f"{d}." if len(rc) == 0 else f"{rc}{d}"
val, k = 100 * (val - k * d), 20 * j
d = next_digit(val, k)
j, k = d + j * 10, k + d
return rc
if __name__ == "__main__":
print(compute_sqrt(2, 1000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment