Babylonian Square Root

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))

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!