Skip to content

Instantly share code, notes, and snippets.

@gunvirranu
Last active May 7, 2021 17:56
Show Gist options
  • Save gunvirranu/51c82c28c77954c15de5c1d55ba8ad0a to your computer and use it in GitHub Desktop.
Save gunvirranu/51c82c28c77954c15de5c1d55ba8ad0a to your computer and use it in GitHub Desktop.
Showcasing float rounding with a very roundabout way of calculating square roots
import math
from decimal import *
# Max precision `prec` you'd want
getcontext().prec = 80
def integral_root(num):
for i in range(int(num) + 1):
if i ** 2 == num:
return i
elif i ** 2 > num:
return i - 1
def funky_sqrt(num, prec):
n = str(integral_root(num)) + "."
for _ in range(prec + 1):
for j in range(1, 10):
test_n = Decimal(n + str(j))
if test_n ** 2 > num:
n += str(j - 1)
break
else:
n += "9"
return Decimal(n)
n = 10002
print("math.sqrt:", math.sqrt(n))
print("this algo:", funky_sqrt(n, 78))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment