-4

I hate Recursive right now. Any way does any one know how to find square root using recursive solution on python. Or at least break it down to simple problems. All examples I found are linear only using one argument in the function. My function needs square Root(Number, low Guess, high Guess, Accuracy) I think the accuracy is supposed to be the base case but I just can't figure out the recursive part.

This is what I have tried:

L = 1
H = 3
def s(n,L,H):
    if (((L + H)/2)**2) <= 0.05:
        print(((L + H)/2))
    else:
        if (((L + H)/2)**2) > 2:
            L = (L + H)/2
            return s(n,L,H)
        else:
            H = (L + H)/2
            return s(n,J,H)
StuartLC
  • 104,537
  • 17
  • 209
  • 285
user3597291
  • 9
  • 1
  • 1

2 Answers2

-1
def sqroot(n,guessed=1.0):

if abs(guessed**2 - n) <= 1e-15 or n == 1:
    return guessed
else:
    guessed = (guessed+ (n/guessed))/2
    return sqroot(n,guessed)
cidms
  • 9
  • 3
-1

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?

Douglas G. Allen
  • 2,203
  • 21
  • 20