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.

JavaScript

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:

JavaScript

You could do a while loop:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement