Write a Python program that calculates the square root of a number using the Babylonian method (or Heron’s method).
Example 1:
Input: 16
Output: 4
Example 2:
Input: 2
Output: 1.41421356
The Babylonian method for square root approximates the square root of a number, n, by repeatedly averaging the values of an overestimate and an underestimate of the square root.
def babylonian_sqrt(n):
x = n
y = (x + n / x) / 2
while abs(y - x) > 0.00000001:
x = y
y = (x + n / x) / 2
return y
print(babylonian_sqrt(16))
print(babylonian_sqrt(2))
NOTEOwing to browser caching, any code input into the Trinket IDE might carry over across page refreshes or when transitioning between different questions. To commence with a clean slate, either click on the 'Reset Button' found within the IDE's Hamburger icon (☰) menu or resort to using Chrome's Incognito Mode.