Lesson goal: Clever way to find pi

Previous: Iterate for a square-root | Home | Next: An even more clever for-loop for Pi

Here's a clever way to find $\pi$ (see Cheney, et. al, 5th ed., p. 39). See if you can translate this "pseudo-code" into a working program to find $\pi$. It'll allow you to practice with for-loops and programming formulas into the computer.

$a\leftarrow\sqrt{2}$
$b\leftarrow 0$
$x\leftarrow 2+\sqrt{2}$
for k=1 to 5 (or more)
$t\leftarrow \sqrt{a}$
$b\leftarrow t(1+b)/(a+b)$
$a\leftarrow \frac{1}{2}(t+1/t)$
$x\leftarrow xb(1+a)/(1+b)$
output x
end-for

Now you try. It's up to you. See if you can translate the pseudo-code into a working program!

Type your code here:


See your results here:

At some point, to test your results, try subtracting your value of $x$ from math.pi and see how close to $0$ you get. Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.