Skip to content

Instantly share code, notes, and snippets.

@rohan-varma
Created March 20, 2022 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohan-varma/65b07aa0526a36f14777942e1b7b12b6 to your computer and use it in GitHub Desktop.
Save rohan-varma/65b07aa0526a36f14777942e1b7b12b6 to your computer and use it in GitHub Desktop.
# Given r, real number in [0, inf)
# Return the sqrt of r without sqrt function
def _mid(left, right):
# Avoiding possible overflow that
# l + r / 2 could cause
return (right - left)/2 + left
def sqrt(r):
# Assumption: r is real and >= 0
if r < 1:
left = r
right = 1
else:
left = 1
right = r
max_iterations = 1000
i = 0
tol = 1e-9
while True:
i+=1
if i == max_iterations:
break
mid = _mid(left, right)
est = mid**2
if abs(r - est) <= tol:
return mid
elif est > r:
right = mid
else:
left = mid
raise ValueError(f"Solution not found after {max_iterations}. Current estimate is {est}")
x = sqrt(.5)
print(x)
print(sqrt(100))
print(sqrt(509))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment