Skip to content

Instantly share code, notes, and snippets.

@letroot
Created June 13, 2015 10:01
Show Gist options
  • Save letroot/76886c538fed94655195 to your computer and use it in GitHub Desktop.
Save letroot/76886c538fed94655195 to your computer and use it in GitHub Desktop.
I wrote a recursive function to compute the square root of a number using the Newton-Raphson method. I am using an inner function, is that a bad thing? How can I use just one function definition?
def r_sqrt(a):
a = float(a)
if a == 0.0:
return 0.0
x = a
def sqrt(x):
epsilon = 0.000000000000001
y = (x + a/x) / 2
if abs(y - x) < epsilon:
return x
else:
return sqrt(y)
return sqrt(a)
@letroot
Copy link
Author

letroot commented Jun 13, 2015

I wrote a recursive function to compute the square root of a number using the Newton-Raphson method. I am using an inner function, is that a bad thing? How can I use just one function definition and still be recursive?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment