APL Pi Day

2025-03-14

Happy \( \pi \) Day

In honor of today’s date, I played around with different ways of approximating everyone’s favorite constant in Dyalog APL. What follows are translations of a few entries from this fun Wikipedia list. I tried to avoid anything that felt like cheating, e.g. using trigonometric functions or other constants like \( \phi \).

First, we set index-origin to its correct value ⎕io←0. Next up, here’s the familiar “throw darts at the unit square” Monte Carlo approach (the first line sets our random seed):

    ⎕rl←1729
    6 1⍴{4×(+⌿÷≢)1>+/×⍨?⍵ 2⍴0}¨10*⍳6
4
3.6
3.12
3.144
3.162
3.1458

Eschewing stochasticity, using Riemann sums for calculating the area of the unit circle converges faster:

      6 1⍴{(4÷×⍨⍵)×+⌿((×⍨⍵)-(×⍨1+⍳⍵))*0.5}¨10*⍳6
0
2.904518326
3.120417032
3.139555467
3.141391478
3.141572616

as does this translation of the first entry in the iterative algorithm from the Wikipedia list (as of this writing), viz.

\[ a_0 = 1, \quad a_{n + 1} = \left(1 + \frac{1}{2n + 1}\right)a_n, \quad \pi = \lim_{n\to\infty}\frac{a_n^2}{n} \]

     6 1⍴{⍵÷⍨×⍨×⌿{1+÷1+2×⍵}⍳⍵}¨10*⍳6
4
3.221088997
3.149456428
3.14237815
3.141671194
3.141600508

Leibniz’s summation \(\sum_0^\infty \frac{(-1)^n}{2n+1}\) converges at a similar rate:

      6 1⍴{4×+⌿(¯1∘*÷(1+2∘×))⍳⍵}¨10*⍳6
4
3.041839619
3.131592904
3.140592654
3.141492654
3.141582654

Though as the corresponding entry notes, this is still sublinear. The fastest one I tried is a slight reworking of

\[ \sum_{n=0}^\infty \frac{(-1)^n}{4}\left(\frac{2}{4n+1}+\frac{2}{4n+2}+\frac{1}{4n+3}\right) \] This is the first entry from the Wikipedia’s list of infinite series which “are efficient for calculating arbitrary binary digits of \(\pi\),” and credited to the book Pi Unleashed.

      15 1⍴{+⌿{((2÷1+4×⍵)+(÷1+2×⍵)+÷3+4×⍵)÷¯4*⍵}⍳⍵}¨⍳15
0          
3.333333333
3.114285714
3.146356421
3.140678766
3.141777944
3.141553701
3.141601054
3.141590807
3.141593065
3.141592561
3.141592675
3.141592649
3.141592655
3.141592653

This is a better approximation in 15 steps than the others reached in a million!