Newton’s Method in Python

def sqrt(n):
    """
    This method calculates the square root
    of a value using Newton's method to an
    accuracy of within sigma.
    """
    sigma = 0.0001

    # The first guess is n / 2
    # (which only works when n is 4)
    guess = n / 2

    while abs(n - guess * guess) > sigma:
        # Compute the quotient
        quotient = n / guess

        # Average the quotient and the current guess
        guess = (quotient + guess) / 2

    return guess

  1. sp0rus reblogged this from jcchurch
  2. jcchurch posted this