Skip to content

Instantly share code, notes, and snippets.

@cdfox
Created September 19, 2014 15:20
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 cdfox/fae8b1484180d6274e44 to your computer and use it in GitHub Desktop.
Save cdfox/fae8b1484180d6274e44 to your computer and use it in GitHub Desktop.
import math
def sqrt(x, high, low, e):
mid = (high + low) / 2.0
square = mid * mid
if (square >= x and square - x <= e) or (square < x and x - square <= e):
return mid
elif square > x:
return sqrt(x, high, mid, e)
else:
return sqrt(x, mid, low, e)
def test_sqrt(x):
print "Square root of %s." % x
print "\t Approx: ", sqrt(x, 1, x, .01)
print "\t Real: ", math.sqrt(x)
if __name__=="__main__":
for x in range(1,11):
test_sqrt(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment