In this post I list some formulas for computing pi with elementary
operations (and square root).

I'll go from worst to best.


First, a horribliy bad formula that gives you three significant
figures for a long computation that takes a whole second on my
computer.

   4*(+/%#),1>+/~*:(i.%])5e3

This also consumes too much memory so is not feasable to run for
larger iteration counts, but we can modify it.  The following variant
needs very little memory, but still gives a very bad approximation.
The increased iteration count here means this one takes about a minute
and gives four significant digits.

   a(a=.2*+/%#)@(1>s&+)"0 s=.*:(i.%])5e4


Now a very slowly converging infinite product.  This is such a bad
approximation it gives you only six significant digits of precision
even with a million terms.  For explanation, see
"http://en.wikipedia.org/wiki/Wallis_product";.

   +:*/*/1 1 _1 _1^~2 2 1 3+/+:i.1e6


Next, a sum that converges slowly so it's not very suitable to compute
pi for precisions higher than machine floats, but that is sufficiently
fast for machine precision.  A hundred thousand iterations give you
double precision, and a hundred iterations already give you six
significant digits.  This formula has a special place in my heart
because I experimented with it on a programmable calculator when I was
young.  For explanation, see
"http://en.wikipedia.org/wiki/Riemann_zeta_function";.

   4%:90*+/_4^~>:i.1e5


We now go to formulas that would be reasonably scalable below machine
float precision.  These two compute sine and cosine using a Taylor
series and use Newton's iteration to converge to pi using that.

   2*(+[:(%~-.)/[:-/_2]\*/\@:%&(>:i.22))^:6]1

   3*(+[:(%~0.5&-)/[:-/_2]\*/\@:%&(>:i.18))^:5]1


Lastly, an efficient and simple computation using the Taylor series of
the arctangent function at tan(pi/12).  The two frets below are based
on the same computation, they're only written differently.

   (($&0 12 0 _12%i.)28)p.2-%:3

   12*-/(2-%:3)(^%])1+2*i.14


The homework to the reader is to implement Plouffe's formula, or other
interesting methods to compute pi.


Ambrus
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to