Streaming Digits of Pi
This page describes a strategy for calculating pi one digit at a time using a streaming algorithm that does not require floating point arithmetic. Although there are more exotic strategies for calculating pi, this one is surprisingly simple to implement, and it streams the digits of pi infinitely. Before we dive in, give it a try in your browser!
Theory
It has long been known that pi can be represented as the product of an infinite series. The Wallis Product published in 1656 represents Pi as:
Which can be expanded to:
And alternatively expressed as:
The paper Spigot Algorithm for the Digits of Pi (1995) by Stanley Rabinowitz and Stan Wagon describes how this infinite product series can be calculated in base 10 to stream the output digit by digit. The algorithm is is described in the paper on page 5. All mathematical operations are achieved using integer arithmetic, completely avoiding issues associated with floating point error accumulation. It is worth noting that the integers are large, so overflows with typical integer data types will occur quickly. It is necessary to use arbitrary length integer data types (BigInt) or to store large integers in an array pre-sized according to the number of digits to be calculated (a little over 3 times the number of digits) which is O(N) space complexity. Because the algorithm requires iterating the array fully for every digit to be calculated, this strategy runs in O(N2) time.
Appendix 2 has a useful bit of code attributed to “Macalester student Simeon Simeonov” implementing the algorithm in Pascal. It notes that this code makes use of the fact that the queue of predigits always has a pile of 9s to the right of its leftmost member, and so only this leftmost predigit and the number of 9s need be remembered.
Pascal Implementation
Program PiSpigot;
const
n = 1000;
len = 10 * n div 3;
var
i, j, k, q, x, nines, predigit: integer;
a: array[1..len] of longint;
begin
for j := 1 to len do
a[j] := 2; {Start with 2s}
nines := 0;
predigit := 0; {First predigit is a 0}
for j := 1 to n do
begin
q := 0;
for i := len downto 1 do {Work backwards}
begin
x := 10 * a[i] + q * i;
a[i] := x mod (2 * i - 1);
q := x div (2 * i - 1);
end;
a[1] := q mod 10;
q := q div 10;
if q = 9 then
nines := nines + 1
else if q = 10 then
begin
write(predigit + 1);
for k := 1 to nines do
write(0); {zeros}
predigit := 0;
nines := 0;
end
else
begin
write(predigit);
predigit := q;
if nines <> 0 then
begin
for k := 1 to nines do
write(9);
nines := 0;
end;
end;
end;
writeln(predigit);
end.
C# Implementation
A line-by-line translation to C# is as follows
int maxDigits = 1000;
int len = (10 * maxDigits) / 3;
int[] a = new int[len + 1];
int nines = 0;
int predigit = 0;
for (int j = 1; j <= len; j++)
a[j] = 2;
for (int j = 1; j <= maxDigits; j++)
{
int q = 0;
for (int i = len; i >= 1; i--)
{
int x = 10 * a[i] + q * i;
a[i] = x % (2 * i - 1);
q = x / (2 * i - 1);
}
a[1] = q % 10;
q /= 10;
if (q == 9)
{
nines++;
}
else if (q == 10)
{
Console.Write(predigit + 1);
for (int k = 1; k <= nines; k++)
Console.Write(0);
predigit = 0;
nines = 0;
}
else
{
if (j > 1)
Console.Write(predigit);
if (j == 2)
Console.Write(".");
predigit = q;
if (nines != 0)
{
for (int k = 1; k <= nines; k++)
Console.Write(9);
nines = 0;
}
}
}
It generates the first thousand digits of pi in about 60 milliseconds. The first 10,000 took 3.3 sec, and additional performance benchmarks can be found at the bottom of this page. The output is accurate according to some online tables I found of pi to a large number of decimal places.
Calculate Pi in your Browser
I implemented the Spigot Algorithm for the Digits of Pi in JavaScript and adapted it to run in the browser. It utilizes JavaScript’s BigInt type to manage math with arbitrarily large integers and runs with a performance comparable to the C# example above.
- Try it Live: Calculate Pi in your browser
- Source Code is on GitHub swharden/Calculate-Pi
Performance of the JavaScript implementation is surprisingly good. You can generate virtually infinite digits of pi using your desktop or mobile device. You never know when you’re going to need a few thousand digits of pi, and it is always good to be prepared.
Performance
This a bak of the envelope test just using my moderate Desktop PC and the C# implementation above, but performance is pretty good for several thousand digits and balloons after that as expected for an algorithm with O(N2) time complexity.
| Digits of Pi | Calculation Time | Approximate Memory |
|---|---|---|
| 1,000 | 62 ms | 13 kB |
| 10,000 | 3.31 sec | 133 kB |
| 100,000 | 4.93 min | 1.3 MB |
| 1,000,000 | 8.12 hr | 13 MB |
Resources
- Source Code (GitHub) for C# and JavaScript projects used on this page
- Spigot Algorithm for the Digits of Pi (1995) is the paper this article is based on
- The Wallis Formula for Pi (2016) By Presh Talwalkar is a nice commentary on the original paper
- Unbounded Spigot Algorithms for the Digits of Pi (2005) by Jeremy Gibbons
- Practical implementation of Spigot Algorithms for Transcendental Constants (2022) by Henrik Vestermark
- Nilakantha’s formula for pi (2023) by Edgar Valdebenito