No! This one is in Ruby. Sorry! But you may easily adapt it. This is a simple version.
One could break this up into more methods perhaps.
For instance:
average
square
good_enough for the guess
improve for the guess
def sqrt(x)
eps = 1.0e-17 # the epsilon desired
diff = 1 # difference of new guess and result
g = 1 # the guess
while (diff > eps) do
xg = x/g
g1 = (g + xg)/2.0
diff = (g - g1).abs
g = g1
end
g
end
p sqrt 2 #=> 1.414213562373095
p Math.sqrt 2 #=> 1.4142135623730951
def good_enough(x, guess)
eps = 1.0e-17
guess2 = square(guess)
(guess2 - x).abs < eps
# true or false
end
def average(x, y)
(x + y) / 2.0
end
and so on.....
It's just an example.
Abstract all that you can so you may use them later.
By the way are you doing MIT OCW by chance?
I'm working on CS 6.001 but that's scheme. It starts out with just this type of processing or procedures. Ruby has lambdas. Can you do lambdas in Python?
Now that I told you about scheme here is that attempt:
(define (square x)
(* x x))
(define epsilon 0.00001)
(define close_enuf?
(lambda (guess x)
(< (abs (- (square guess) x)) epsilon)))
(define (average x y)
(/ (+ x y) 2.0))
(define improve
(lambda (guess x)
(average guess (/ x guess))))
(define sqrt_loop
(lambda (guess x)
(if (close_enuf? guess x)
guess
(sqrt_loop (improve guess x) x))))
(define sqrt
(lambda (x)
(sqrt_loop 1.0 x)))
Not too hard to read is it?