BABYLON
This page runs a BASIC program that finds \(\sqrt{5}\) using a method known to the Babylonians nearly 4,000 years ago. The program is rewritten in Python and runs right here in your browser. Edit the code and press Run to run it again; Reset brings back the original program.
Start with a guess, x = 2. If x is too small, then 5/x is too large, and the other way around, so the true square root lies between them. Their average,
\[ x_{\text{new}} = \frac{1}{2}\left(x + \frac{a}{x}\right), \]
is a better guess. The loop does this n = 6 times and prints each new guess. The guesses are 2.25, then 2.2361111…, then 2.2360679779…, and from the fourth step on the printed value no longer changes: 2.23606797749979 is \(\sqrt{5}\) to every digit the computer keeps. Notice how fast this is. Roughly, the number of correct digits doubles with each step. (Later in the course this turns out to be Newton’s method applied to \(x^2 - a = 0\).)
Try other values of a, a bad starting guess such as x = 100, or x = -2 to see which square root you end up with. Nothing in this program needs anything special in Python; only FOR k = 1 TO n becomes for k in range(1, n + 1):.
Notes from the textbook
Add notes here.
1 DEFDBL A-Z
2 a = 5
3 x = 2
4 n = 6
5 FOR k = 1 TO n
6 x = (x + a / x) / 2
7 PRINT x
8 NEXT k
Output
Everything the program prints appears here, one line for each print(...),
like BASIC's PRINT. Numbers printed on the same line are lined up in columns.
Python code
Press Run (or Ctrl/⌘ + Enter) to run the program again. Press Esc, then Tab, to leave the editor.