Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- x = 23493
- class SquareRootResult(Exception):
- def __init__(self, number, sqrt):
- self.number = number
- self.sqrt = sqrt
- def Iterate(x, guess):
- guessedX = guess * guess
- difference = x - guessedX
- if difference > -0.0001 and difference < 0.0001:
- raise SquareRootResult(number=x, sqrt=guess)
- newGuess = 0.5 * (guess + (x / guess))
- return newGuess
- def GetInitialGuess(x):
- # Unimportant code. From Wikipedia:
- # "one starts with an initial guess which is reasonably close to the true root"
- import math
- return math.sqrt(x)
- numIterations = 0
- try:
- guess = GetInitialGuess(x)
- while True:
- numIterations += 1
- guess = Iterate(x, guess)
- except SquareRootResult as e:
- print "Square root of", e.number, "is", e.sqrt, "in", numIterations, "iterations."
- except:
- print "This number has no square root after", numIterations, "iterations."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement