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
x
19
19
1
Repeat = True
2
while Repeat == True:
3
og = float(input("What do you want to find the square root of?: "))
4
print("Okay, we will use the Babylonian algorithm to find the square root of " + str(og) + ".")
5
guess = float(input("Roughly estimate what the square root of " + str(og) + " is: "))
6
print("Each answer will get closer to the true square root.")
7
for answer in range(1,15):
8
answer = ((guess + (og/guess))/2)
9
print(answer)
10
guess = (answer)
11
else:
12
print("The square root of " + str(og) + " is roughly " + str(answer) + ".")
13
end = input("Do you want to find the square root of another number? y/n: ")
14
if end == 'y':
15
Repeat = True #This repeats the program
16
else:
17
Repeat = False #This ends the 'Repeat' loop.
18
print("Okay, thank you for using my program!")
19
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
1
5
1
for answer in range(1,15):
2
answer = ((guess + (og/guess))/2)
3
print(answer)
4
guess = (answer)
5
You could do a while loop:
JavaScript
1
6
1
import math
2
real_answer=math.sqrt(og)
3
while abs(real_answer-guess)<=x: #x is how close you want your guess to be to the real answer
4
guess=(guess+(og/guess))/2
5
print(guess)
6