Skip to content

Instantly share code, notes, and snippets.

@iamakimmer
Last active December 12, 2015 08:59
Show Gist options
  • Save iamakimmer/4748382 to your computer and use it in GitHub Desktop.
Save iamakimmer/4748382 to your computer and use it in GitHub Desktop.
2 different methods of calculating Square Root. First is the Newton/Raphson method and the second is the Heron of Alexandria's Method. It seems like Heron of Alexandria's method is simpler but just as fast. However I'm getting an infinite loop on large numbers or my computer hates the heron method on really big numbers. What am I doing wrong?
#newton-raphson for sq root
def newton(square):
guess = square/2.0
attempts = 0
# f(x) = x**2 - square
# then f'(x) = 2x
while abs(guess*guess) - square >= .001:
# print guess
attempts+=1
guess = guess - ((guess**2 - square)/(2*guess))
print 'The square root of', square, 'is about', guess, ' in ', attempts, 'attemps using Newton-Raphson\'s method.'
#heron
def heron(square):
guess = square/2.0
attempts = 0
while abs(guess*guess) - square >= .001:
attempts+=1
guess = (guess + square/guess) / 2
print 'The square root of', square, 'is about', guess, ' in ', attempts, 'attemps using Heron of Alexandria\'s method.'
heron(2199932523532522322)
newton(2199932523532522322)
newton(3999932523532522322)
# heron(3999932523532522322) this goes into infinite loop, or something else
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment