Advertisement
Guest User

Newton-Raphson O(1)

a guest
Feb 13th, 2015
3,412
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. x = 23493
  2.  
  3.  
  4. class SquareRootResult(Exception):
  5.     def __init__(self, number, sqrt):
  6.         self.number = number
  7.         self.sqrt = sqrt
  8.  
  9.  
  10. def Iterate(x, guess):
  11.     guessedX = guess * guess
  12.  
  13.     difference = x - guessedX
  14.     if difference > -0.0001 and difference < 0.0001:
  15.         raise SquareRootResult(number=x, sqrt=guess)
  16.  
  17.     newGuess = 0.5 * (guess + (x / guess))
  18.     return newGuess
  19.  
  20.  
  21. def GetInitialGuess(x):
  22.     # Unimportant code. From Wikipedia:
  23.     # "one starts with an initial guess which is reasonably close to the true root"
  24.     import math
  25.     return math.sqrt(x)
  26.  
  27.  
  28. numIterations = 0
  29.  
  30. try:
  31.     guess = GetInitialGuess(x)
  32.     while True:
  33.         numIterations += 1
  34.         guess = Iterate(x, guess)
  35. except SquareRootResult as e:
  36.     print "Square root of", e.number, "is", e.sqrt, "in", numIterations, "iterations."
  37. except:
  38.     print "This number has no square root after",  numIterations, "iterations."
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement