Grant Kaylock
Grant Kaylock

Reputation: 31

Loop Function to find a Square root of a number

The question is To find the square root of number ‘N’.using this procedure, we must implement the following process:

  1. Guess a value for the square root of N
  2. Divide N by that guess
  3. Average the result with your original guess to get your new guess
  4. Go to step 2 and repeat

I have set the code to return the Guess once it is within 0.5 of the previous Guess, and if its not to repeat the function. I'm not sure how to make it repeat or how to close the loop.

def SqrRt(Number,Guess):
while Guess2 == ((Estimate+Guess)/2):
    if (Estimate - Guess2) <= 0.5:
        return Guess2
    elif (Estimate - Guess2) >= -0.5:
        return Guess2
    else:
       Estimate = (Number/Guess)
    Guess2 = Estimate + 1

answer = SqrRt(34567823321421,500000) print(answer)

Upvotes: 1

Views: 5985

Answers (2)

Frank-Rene Sch&#228;fer
Frank-Rene Sch&#228;fer

Reputation: 3352

Using the Babylonian Method means solving (S^2 - V) = 0. Here, S is the square root of V, which is to be found. Applying Newtons Approximation leads to an iterative method where 'x_new = (x_prev + V / x_prev) / 2'. The first 'x_prev' needs to be estimated.

The iteration converges monotonously. Thus a check against a delta in development is sufficient.

x      = V / 2.0       # First estimate
prev_x = x + 2 * Delta # Some value for that 'while' holds
while abs(prev_x - x) > Delta:
    prev_x = x
    x      = (x + V/x) / 2.0
square_root = x

Choose Delta to be arbitrarily small (e.g. 0.0001).

Upvotes: 4

Jachdich
Jachdich

Reputation: 792

First off

You need code that will actually run at all for a question like this. I suggest that your code should look more like this:

def SqrRt(Number,Guess):
    while Guess2 == ((Estimate+Guess)/2):
        if (Estimate - Guess2) <= 0.5:
            return Guess2
        elif (Estimate - Guess2) >= -0.5:
            return Guess2
        else:
           Estimate = (Number/Guess)
        Guess2 = Estimate + 1
answer = SqrRt(34567823321421,500000)
print(answer) 
#Number to Use - 34567823321421
#Answer - 5879440.732

Upvotes: 0

Related Questions