Search code examples
c#piarbitrary-precision

Calculate Pi with arbitrary precision digit by digit


So I want to output Pi with arbitrary precision digit by digit. I found some code here https://rosettacode.org/wiki/Pi#C.23

public IEnumerable<long> PiDigits(long b = 10)
    {
        BigInteger
            k = 1,
            l = 3,
            n = 3,
            q = 1,
            r = 0,
            t = 1
            ;

        // skip integer part
        var nr = b * (r - t * n);
        n = b * (3 * q + r) / t - b * n;
        q *= b;
        r = nr;

        for (; ; )
        {
            var tn = t * n;
            if (4 * q + r - t < tn)
            {
                yield return (long)n;
                nr = b * (r - tn);
                n = b * (3 * q + r) / t - b * n;
                q *= b;
            }
            else
            {
                t *= l;
                nr = (2 * q + r) * l;
                var nn = (q * (7 * k) + 2 + r * l) / t;
                q *= k;
                l += 2;
                ++k;
                n = nn;
            }
            r = nr;
        }
    }

And it's working correctly but there's no explanation to it. I want to understand this algorithm but it looks too complicated. And variables' name don't give me anything. So could you please tell me what algorithm is that co I could continue my research. Thank you!


Solution

  • This is an implementation of the spigot algorithm translated from an implementation by Jeremy Gibbons.

    His paper explains the inner workings of the algorithm. You should find the information you need at pages 5 and 6.