Skip to content
Advertisement

How to stop a python loop when it hits the range of a specific number?

Our assignment is to find the square root of number inputed by the user by using the Babylonian algorithm. The babylonian algorithm is (guess+input/guess)/2. I am using a loop and replacing the ‘guess’ with the answer of the previous iteration.

What I want to do is to stop the loop once it is within 10x^-15 of the true square root and print the answer.

Repeat = True
while Repeat == True:
    og = float(input("What do you want to find the square root of?: "))
    print("Okay, we will use the Babylonian algorithm to find the square root of " + str(og) + ".")
    guess = float(input("Roughly estimate what the square root of " + str(og) + " is: "))
    print("Each answer will get closer to the true square root.")
    for answer in range(1,15):
        answer = ((guess + (og/guess))/2)
        print(answer)
        guess = (answer)
    else:
    print("The square root of " + str(og) + " is roughly " + str(answer) + ".")
    end = input("Do you want to find the square root of another number? y/n: ")
    if end == 'y':
            Repeat = True #This repeats the program
        else:
            Repeat = False #This ends the 'Repeat' loop. 
            print("Okay, thank you for using my program!")

Currently, I have it to repeat a set amount of times (15). But like I said, I would like it to repeat not for a set number of times, but until it gets within a certain amount of the true answer.

Advertisement

Answer

Instead of this:

for answer in range(1,15):
    answer = ((guess + (og/guess))/2)
    print(answer)
    guess = (answer)

You could do a while loop:

import math
real_answer=math.sqrt(og)
while abs(real_answer-guess)<=x: #x is how close you want your guess to be to the real answer
    guess=(guess+(og/guess))/2
    print(guess)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement