Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Created December 6, 2022 16:26
Show Gist options
  • Select an option

  • Save EteimZ/858c18208a8806dbeea4e68032cea9cc to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/858c18208a8806dbeea4e68032cea9cc to your computer and use it in GitHub Desktop.
The babylonian method used to calculate the square root of a number
# Number to calculate its square root
n = 25
# Initial guess
x0 = (n + 1)/2
# maximum number of iterations
max_iter = 30
# Difference threshold
threshold = 0.0000001
# Calculate the square root using Babylonian method
for i in range(30):
# Next guess
x1 = (x0 + n/x0)/2
# Check if difference is small enough
if abs(x1 - x0) < threshold:
break
# Update initial value
x0 = x1
print(x1)
# 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment