newton's square root
# A simple way to estimate a square root (if you cannot use a sqrt function).
#
# Example usage (prompts for the number if none passed as argument):
# $ python sqrt.py 12313
# estimated = 110.963958113, actual = 110.963958113
from __future__ import division
import math
from sys import argv
def newtons_method(num):
"""Newton's Method for finding a square root.
http://www.quora.com/Mathematics/How-can-I-find-the-square-root-of-22-without-a-calculator
"""
guess = num / 10 # An arbitrary guess, we need to start somewhere.
for _ in xrange(10):
guess = 0.5 * (guess + (num / guess)) # Improve the guess.
print 'estimated = {}, actual = {}'.format(guess, math.sqrt(num))
try:
num = int(argv[1])
except:
num = input('Enter a number: ')
newtons_method(num)