First, design and implement a Python program that takes a positive whole number
ID: 674980 • Letter: F
Question
First, design and implement a Python program that takes a positive whole number n as input and outputs the square root of n using the Babylonian algorithm. The Babylonian algorithm computes the square root of a positive number, n, as follows: Make a guess at the answer (you can pick n/2 as your initial guess). Compute r = n / guess. Set guess = (guess + r) / 2 Go back to step 2 for as many iterations as necessary. The more steps 2 and 3 are repeated, the closer guess will become to the square root of n. Compare your calculated square root with the math.sqrt () result USE WHILE LOOPExplanation / Answer
def babylonian(n, steps):
count = 0;
guess = n/2
while(count < steps):
r = n/guess
guess = (guess+r)/2.0
if(guess == r):
break;
#print ('num =, squreroot = , r= ', n, guess, r)
count = count+1
return guess
num = 2;
root = babylonian(num, 5)
root10 = babylonian(num, 10)
import math
rootByMath = math.sqrt(num)
print('Root of ', num)
print('Using babylonian ( 5 steps): ',root)
print('Using babylonian ( 10 steps): ',root10)
print('Using math.sqrt: ',rootByMath)
---------------output--------------------------
sh-4.3$ python main.py
('Root of ', 2)
('Using babylonian ( 5 steps): ', 1.414213562373095)
('Using babylonian ( 10 steps): ', 1.414213562373095)
('Using math.sqrt: ', 1.4142135623730951)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.