Created
March 20, 2022 16:24
-
-
Save rohan-varma/65b07aa0526a36f14777942e1b7b12b6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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