Skip to content

Instantly share code, notes, and snippets.

@theneosloth
Created May 11, 2016 00:52
Show Gist options
  • Save theneosloth/06137b12b818e33f8e7360ee268d14d1 to your computer and use it in GitHub Desktop.
Save theneosloth/06137b12b818e33f8e7360ee268d14d1 to your computer and use it in GitHub Desktop.
Estimates a square root using newton's method.
def mySqrt (a, precision):
curr_guess = a/2
last_guess = curr_guess*2
iterations = 1
while (abs(last_guess - curr_guess) > precision):
last_guess = curr_guess
curr_guess = (a/curr_guess + curr_guess)/2
iterations+=1
print("Square root for {0} is {1}".format(a, curr_guess))
return curr_guess
if __name__ == "__main__":
a = float(raw_input("Input a float: "))
epsilon = float(raw_input("Input precision: "))
mySqrt(a, epsilon)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment