SAVANT//GATEWAY
Back to Signal
ArticleLobstersNov 24, 2026stylewarning.com via lordgilman

A faster algorithm for extracting hexadecimal digits of π

A faster algorithm for extracting hexadecimal digits of π

November 24, 2026 · Last updated November 26, 2026

By Robert Smith

This post introduces a new algorithm for extracting hexadecimal digits of \(\pi\) without computing the preceding digits. It beats the standard term-by-term evaluations of Bailey–Borwein–Plouffe (BBP), Bellard, and Huvent on operation count by a substantial margin.


Contents

  1. The BBP trick and formula convergence
  2. Lining up denominators
  3. Four powers in two exponentiations
  4. Sharing work across denominators
    1. Grouping by denominator pairing
    2. Grouping by prime powers
  5. Notes on a high-performance implementation
    1. SIMD with paired denominators
    2. SIMD with prime powers
  6. A pedagogical Common Lisp implementation

The key insights come from the following identity:

\[ \boxed{ \pi = \sum_{k=0}^{\infty} \frac{(-1)^{\lfloor k/2\rfloor}\big(2^{1-3k}+2^{-1-5k}\big) + (-1)^k\big(2^{-1-6k}+2^{-4-10k}\big)}{2k+1}. } \]

The underlying series goes back to Euler, but I’ve rearranged it to exploit more efficient evaluation. Collecting its terms by odd denominators lets us share the arithmetic in two places:

  1. The common denominator \(M=2k+1\) means we can add four remainders and divide once. The surprise is that we don’t have to compute those remainders independently either. The gaps between the exponents are small multiples of \(k\) plus constants, so one starting power and the step \(2^k\bmod M\) let us reach the others by multiplication.

  2. We can also share arithmetic between denominators by using their common factors. We show two ways to do that:

    • Group by denominator pairs: When \(M\) and \(3M\) are both in range, work modulo \(3M\). Two full exponentiations give us up to eight powers of two, and we still divide just once.
    • Group by prime powers: Split each fraction over the prime powers in its denominator. All contributions over the same prime power share one modular exponentiation and one division. The sieve uses asymptotically more memory than pairing, but its running time is also asymptotically improved.

In my AVX-512 implementation, I timed the extraction of 12 hexadecimal digits after skipping the first trillion. On 32 threads, denominator pairing was 1.62× as fast as Huvent and prime-power grouping was 5.56× as fast.

The BBP trick and formula convergence

To see where the savings come from, let’s recall the BBP trick. To skip \(n\) hex digits, shift \(\pi\) left by \(d=4n\) bits and take the fractional part. Shifting by \(d\) bits adds \(d\) to each exponent, so we’re left adding and subtracting terms of the form \(2^E/N\). When \(E\ge 0\), write \(2^E=qN+r\). Then \(2^E/N=q+r/N\), and we don’t care about \(q\): it’s an integer. Even at \(d=4{,}000{,}000\), we can compute \(r=2^E\bmod N\) without ever constructing a four-million-bit numerator.

The terms with \(E<0\) make up the tail. They decay geometrically, so we sum them directly, keeping enough guard bits to settle the last digit we want.

The above is essentially the BBP trick, and is the basis for three decades of digit extraction algorithms.

As such, when I was programmatically looking for efficient BBP-formula, I ranked them by how many fractions I’d have to evaluate to reach a given digit. Each fraction in the main loop costs me a modular exponentiation and a division. Bellard’s formula advances 10 bits for every seven fractions; Huvent’s formula advances 12 bits for every eight. After finding Huvent’s formula independently, I’ve tried feverishly to find one with a better ratio, without success. So I looked toward ways of optimizing existing series.

One clue tipped me off. There’s a choice hiding in the last step of Bellard’s terse derivation. He has one sum in powers of \(1/4\) and another in powers of \(1/1024\). Since \(4^5=1024\), splitting the first sum into five progressions lets him write both sums in powers of \(1/1024\). What if, instead of lining up the powers, we lined up the denominators?

Lining up denominators

Lining up denominators seemed hard with the many-term series of Bellard and Huvent. One good place I found to try this is a series Euler wrote down in 1779, as noted by Craig-Wood, who used it himself to write an extraction program1. The starting point is Hutton’s arctangent identity (which Bellard lists):

\[ 2\arctan\left(\frac13\right)+\arctan\left(\frac17\right)=\frac\pi4. \]

One way to check it is to multiply out \((3-i)^2(7-i)=50(1-i)\) and take the argument of each side. The usual Taylor series for these arctangents would give us powers of 3 and 7. To get powers of two, it helps that \(3=4-1\) and \(7=8-1\).

Consider \(3-i\) for example. Its argument is \(-\arctan(1/3)\). Dividing by four doesn’t change the angle, but it does put the number in a useful form: \((3-i)/4=1-(1+i)/4\). Likewise, \((7-i)/8=1-(1+i)/8\). The imaginary part of a logarithm is the argument, so taking minus the logarithm and keeping its imaginary part gives us the positive angle in each case. Expanding \(-\log(1-z)=\sum_{j=1}^{\infty}z^j/j\), we get

\[ \begin{aligned} F(a) := \arctan\left(\frac{1}{a-1}\right) &= \operatorname{Im}\left[-\log\left(1-\frac{1+i}{a}\right)\right] \\ &= \sum_{j=1}^{\infty}\frac{\operatorname{Im}\big((1+i)^j\big)}{j\,a^j}. \end{aligned} \]

This converges absolutely for both \(a=4\) and \(a=8\), since \(\lvert 1+i\rvert=\sqrt{2}<a\). Hutton’s identity, multiplied by four, now reads \(\pi=8F(4)+4F(8)\).

The first four powers of \(1+i\) are \(1+i,\;2i,\;-2+2i,\;-4\). Their imaginary parts are \(1,2,2,0\): only three terms in each block of four survive. Since the fourth power is \(-4\), increasing \(j\) by four multiplies \((1+i)^j/a^j\) by \(-4/a^4\). That’s \(-1/64\) in \(F(4)\) and \(-1/1024\) in \(F(8)\). Each arctangent gives us three rows, one for each of \(4m+1,\;4m+2,\;4m+3\). For instance, the \(j=1,5,9,\ldots\) row of \(8F(4)\) starts with \(8/4=2\), then \(-2/(5\cdot64)\). In Euler’s formulation the six rows read:

\[ \begin{aligned} \pi ={}& 2\left(1 - \frac{1}{5}\cdot\frac{1}{64} + \frac{1}{9}\cdot\frac{1}{64^2} - \frac{1}{13}\cdot\frac{1}{64^3} + \cdots\right) \\ &+ \frac{1}{2}\left(1 - \frac{1}{3}\cdot\frac{1}{64} + \frac{1}{5}\cdot\frac{1}{64^2} - \frac{1}{7}\cdot\frac{1}{64^3} + \cdots\right) \\ &+ \frac{1}{4}\left(\frac{1}{3} - \frac{1}{7}\cdot\frac{1}{64} + \frac{1}{11}\cdot\frac{1}{64^2} - \frac{1}{15}\cdot\frac{1}{64^3} + \cdots\right) \\[4pt] &+ \frac{1}{2}\left(1 - \frac{1}{5}\cdot\frac{1}{1024} + \frac{1}{9}\cdot\frac{1}{1024^2} - \frac{1}{13}\cdot\frac{1}{1024^3} + \cdots\right) \\ &+ \frac{1}{16}\left(1 - \frac{1}{3}\cdot\frac{1}{1024} + \frac{1}{5}\cdot\frac{1}{1024^2} - \frac{1}{7}\cdot\frac{1}{1024^3} + \cdots\right) \\ &+ \frac{1}{64}\left(\frac{1}{3} - \frac{1}{7}\cdot\frac{1}{1024} + \frac{1}{11}\cdot\frac{1}{1024^2} - \frac{1}{15}\cdot\frac{1}{1024^3} + \cdots\right). \end{aligned} \]

Takahashi writes this more straightforwardly as two sums distinguished by their exponential factors:

\[ \begin{aligned} \pi ={}& \frac{1}{4}\sum_{m=0}^{\infty} \left(-\frac{1}{64}\right)^m \left(\frac{8}{4m+1}+\frac{4}{4m+2}+\frac{1}{4m+3}\right) \\[4pt] &+ \frac{1}{64}\sum_{m=0}^{\infty} \left(-\frac{1}{1024}\right)^m \left(\frac{32}{4m+1}+\frac{8}{4m+2}+\frac{1}{4m+3}\right). \end{aligned} \]

Notice the denominators of the fractions. Since \(4m+2=2(2m+1)\), we can halve the numerator of the middle fraction and leave \(2m+1\) in the denominator. As \(m\) runs over the nonnegative integers, \(2m+1\) gives every positive odd integer. The other two progressions, \(4m+1\) and \(4m+3\), split that same list between them. So each odd denominator appears twice in each sum.

For example, consider the denominator 13. The first progression hits it at \(m=3\); the middle one hits it at \(m=6\), where the original denominator was 26. That’s two contributions from the sum in powers of \(1/64\) and two from the sum in powers of \(1/1024\). The powers are different, but all four numerators can be added before we divide by 13.

Now write the odd denominator as \(2k+1\). The middle fraction reaches it at \(m=k\), so after halving the middle numerators their sum is

\[ \frac12\left(-\frac1{64}\right)^k+\frac1{16}\left(-\frac1{1024}\right)^k =(-1)^k\big(2^{-1-6k}+2^{-4-10k}\big). \]

For the outer two fractions, follow the odd denominators \(1,3,5,7,\ldots\) in order. In the first sum the numerators go \(2,\;1/4,\;-2/64,\;-1/(4\cdot64),\ldots\). Each is one eighth the magnitude of the last, but the sign changes only every two entries, when \(m\) advances. In the second sum the magnitudes start at \(1/2\), then \(1/64\), shrinking by a factor of 32 each time, with the same signs. So at \(2k+1\) their magnitudes are \(2(1/8)^k=2^{1-3k}\) and \(\tfrac12(1/32)^k=2^{-1-5k}\), and their common sign is \((-1)^{\lfloor k/2\rfloor}\). Along with the two middle numerators, that’s all four powers in the boxed formula.

Four powers in two exponentiations

After the shift by \(d\), that is, multiplying the sum by \(2^d\), the four exponents, in the order we wrote them, are

\[ (E_1,E_2,E_3,E_4)=(d+1-3k,\ d-1-5k,\ d-1-6k,\ d-4-10k). \]

Call a power active if its exponent is nonnegative. The slowest-decaying exponent is \(E_1\), which stays nonnegative up to \(k=\lfloor(d+1)/3\rfloor\). That’s about \(d/3\) odd denominators, and we divide just once for each one. Even the largest modulus is only \(2d/3+O(1)\), compared with about \(d\) for Bellard or Huvent, and \(2d\) for the original BBP formula.

As for the remainders \(r_j=2^{E_j}\bmod N\), notice that the middle two exponents differ by \(k\). If we already have \(r_3\) and \(x=2^k\bmod N\), then \(r_2\) is just \(xr_3\bmod N\). In fact, we can step from the smallest exponent up to the largest:

\[ r_4 \;\xrightarrow{\;\times\,8x^4\;}\; r_3 \;\xrightarrow{\;\times\,x\;}\; r_2 \;\xrightarrow{\;\times\,4x^2\;}\; r_1 \pmod N. \]

Start at the smallest active power. We pay for one full exponentiation to get it and one to get \(x\); the rest are a handful of multiplications. Past \(k\approx d/5\) only \(E_1\) is active, so don’t bother computing \(x\).2 That’s two exponentiations for the first \(d/5\) denominators and one for the remaining \(d/3-d/5\), or about \(8d/15\) altogether.

Sharing work across denominators

So far we’ve shared exponentiations among terms with the same denominator. We can also share them across denominators. We show two ways of doing this. The simpler way is to pair \(M\) with \(3M\), which saves a constant fraction of the work and needs only a few words of memory. With a sieve, we can go further: split each fraction into terms with prime-power denominators, then add up the numerators for each such power. A well-implemented sieve uses asymptotically more working memory than pairing, but its total running time is asymptotically better.

Grouping by denominator pairing

So far we’ve paid for one division by 13 and another by 39. Call the signed sums of their active powers \(A\) and \(B\). Since 39 is three times 13, their combined contribution is

\[ \frac{A}{13}+\frac{B}{39}=\frac{3A+B}{39}. \]

We only want the fractional part, so we can compute both numerators modulo 39, take the remainder of \(3A+B\), and divide by 39 just once.

Now consider the step powers. For 13 the index is 6; for 39 it’s 19. Since \(19=3\cdot6+1\), once we have \(x=2^6\bmod39\), we get the step for 39 by cubing and doubling: \(2^{19}\equiv2x^3\pmod{39}\).

In general, tripling a denominator \(M=2k+1\) changes its index from \(k\) to \(3k+1\). Substitute that index into the four exponents above to get the partner’s exponents. Now read the active exponents from both numerators in increasing order. The common \(d\) cancels in every gap, leaving a small multiple of \(k\) plus a constant. We need just two full exponentiations modulo \(3M\): one for the first power in the list and one for the step \(2^k\). Multiplication takes us up the rest of the list.

We never need to compute the step just for \(3M\). Its largest exponent, \(d-2-9k\), is smaller than the second exponent for \(M\), \(d-1-5k\). If \(3M\) has even one active power, \(M\) already has at least two.

We don’t want to pair 39 with 13 and then pair it again with 117. So we start pairs only at odd \(M\) not divisible by three. If \(3M\) has an active power, we take it with \(M\); otherwise we process \(M\) alone. Odd multiples of nine, like 117, stay unpaired.

The denominators that no longer need their own turn are precisely the odd multiples of three that aren’t multiples of nine. That’s two out of every nine odd denominators, both where we need one exponentiation and where we need two. Multiplying the counts above by \(7/9\) gives about \(7d/27\) divisions and \(56d/135\) full exponentiations, compared to \(2d/3\) of each for Huvent.

Grouping by prime powers

(Edit 25 Nov 2026: My first implementation of prime-power grouping built large sieves and didn’t vectorize well. While it did far fewer exponentiations, the pairing optimization was still much faster at the offsets I could reasonably compute, so I left this section out of the original post. Some discussion comments3 prompted me to revisit my implementation and reinstate this section.)

For a fixed digit window at bit offset \(d\), a segmented sieve can reduce the work from \(O(d\log d)\) to \(O(d\log\log d)\) word operations, at the cost of \(O(\sqrt d)\) bits of working space instead of \(O(\log d)\).

We start with the same boxed formula for \(\pi\), multiply by \(2^d\), and sum the terms with negative exponents as before. Call that tail \(T_d\). What changes is how we collect the remaining fractions. Take the signed numerators \(A\) and \(B\) over 13 and 39. The \(M\)-\(3M\) paired loop puts both over 39. The sieve goes the other way: it splits \(1/39\) into fractions over 3 and 13.

For digit extraction we only need the split to hold modulo one: the two sides can differ by an integer. Writing \(r/3+s/13\) back over 39, that means its numerator \(13r+3s\) must equal 1 modulo 39. Modulo 3, the \(3s\) term drops out and we get \(r\equiv1\pmod 3\). Modulo 13, the \(13r\) term drops out and we get \(3s\equiv1\pmod{13}\), so \(s=9\) works. Since 3 and 13 are coprime, the Chinese remainder theorem tells us that matching both remainders is enough to match modulo 39.

Indeed, \(1/3+9/13=40/39\), exactly one too large. Using \(-4\) instead of 9 subtracts that one and gives \(1/39=1/3-4/13\). Multiply by \(B\) and add \(A/13\), and we get

\[ \underbrace{\frac{3A+B}{39}}_{\text{paired loop}} = \frac{A}{13}+\frac{B}{39} = \underbrace{\frac{A-4B}{13}+\frac{B}{3}}_{\text{prime-power grouping}}. \]

So the fraction over 39 contributes \(-4B\) to the numerator over 13. Fractions over 65 and 91 also contribute there. To split any \(B/M\), write \(M\) as a product of (coprime) prime powers. For each such factor \(q\), put \(u=M/q\). When we put \(r/q\) back over \(M\), its numerator becomes \(ur\). The other fractions in the split all pick up a factor of \(q\) in their numerators, so we just need \(ur\equiv B\pmod q\). Since \(u\) and \(q\) are coprime, \(r=Bu^{-1}\bmod q\) is the numerator to add over \(q\).

We don’t need to evaluate \(A\) and \(B\) before splitting them. Each shifted power has the form \(2^{d+b}\). Modulo an odd prime power \(q\), we can factor out \(2^d\) even when \(b\) is negative, since 2 has an inverse. Let \(C_q(d)\) be the sum, modulo \(q\), of the coefficients left after factoring out \(2^d\). Writing braces for the fractional part, we get

\[ \{2^d\pi\} = \left\{T_d+\sum_q \frac{2^d C_q(d)\bmod q}{q}\right\}, \]

where \(q\) runs over the prime powers in the active denominators. One computation of \(2^d\bmod 13\) serves every contribution over 13, but to get that saving we have to find the contributing multiples and assemble their coefficient.

Notes on a high-performance implementation

Here is how far into \(\pi\) each method gets per expensive arithmetic operation, with the offset \(d\) measured in bits:

FormulaBits per full mod. exp.Bits per division
BBP, term by term4/4 = 1.004/4 = 1.00
Euler, term by term5/4 = 1.255/4 = 1.25
Bellard, term by term10/7 ≈ 1.4310/7 ≈ 1.43
Huvent, term by term12/8 = 1.5012/8 = 1.50
This post (\(M\)-\(3M\))135/56 ≈ 2.4127/7 ≈ 3.86
This post (primes)\(\Theta(\log d)\)\(\Theta(\log d)\)

I implemented the last three methods using AVX-512 IFMA. Here are some benchmarks for extracting 12 hex digits on my Ryzen AI Max+ PRO 395, including sieve setup for the primes column. Both “% faster” columns are relative to Huvent.

Hex digits skippedThreadsHuvent\(M\)–\(3M\)% fasterPrimes% faster
1,000,000110.9 ms6.24 ms+74.8%4.70 ms+132.3%
100,000,00011.23 s731 ms+68.4%273 ms+351.1%
1,000,000324.03 ms3.73 ms+8.3%3.76 ms+7.2%
100,000,0003263.0 ms39.6 ms+59.1%16.2 ms+290.3%
1,000,000,00032678 ms416 ms+62.8%119 ms+468.5%
1,000,000,000,0003214m 6s8m 41s+62.3%2m 32s+456.2%

SIMD with paired denominators

Returning to the pair 13 and 39, while 39 is active, I never reduce modulo 13: changing the numerator for 13 by a multiple of 13 changes its tripled contribution by a multiple of 39. So I do all the squaring and multiplying modulo 39. Since 39 is odd, I can compute its inverse modulo a power of two once and reuse it for every Montgomery multiplication in the pair. I triple the numerator for 13, add the one for 39, and convert back from Montgomery form just once for the final division.

There’s a nice trick inside each exponentiation, too. Suppose a Montgomery reduction leaves \(-14\) modulo 39. Normally I’d add 39 to get 25. But if I’m going to square it next, 14 is just as good: \(14^2\equiv25^2\pmod{39}\). Even if the current exponent bit calls for doubling first, the next square still erases the sign. So for all but the last bit, I use vector absolute values instead of correcting the sign. On the last bit I do the usual reduction, since the numerator needs the actual residue rather than its negative. That change made the exponentiation loop about 8% faster on Zen 5.

Each vector lane handles a different odd modulus. I batch moduli with the same set of active powers so that one lane doesn’t sit idle while another steps through three extra residues. The hardware multiplies 52-bit inputs, so the largest modulus matters: ours is about \(2d/3\), compared with \(d\) for Huvent. That lets us reach about 50% farther into \(\pi\) before we need wider arithmetic.

SIMD with prime powers

Each worker sieves a 32 KiB block of odd numbers at a time. For small sieving primes the positions to cross out repeat, so I OR their bit masks into the block a word at a time. For the other sieving primes I keep track of the next multiple to cross out. If a prime skips whole blocks, I put it in a bucket for the next block it hits. That way I don’t have to scan the whole list of sieving primes for every block. The primes left in the block go to the arithmetic loop, one prime \(p\) per vector lane.

Let \(L\) be the largest active denominator. If \(p>L/17\), its only possible odd cofactors are \(1,3,\ldots,15\). Primes for which the same cofactors occur in each of the four sums share a rational coefficient up to a sign. I batch those primes together: eight vectors of eight lanes can follow the same exponent bits, each lane reducing modulo its own prime. There’s no loop over cofactors in this batch. At a billion hex digits skipped, about 93% of the primes take this path.

For the medium-sized primes, each lane keeps a running fraction \(a/b\) modulo \(p\). To add \(v/u\), it forms \((au+bv)/(bu)\) rather than computing an inverse for every \(u\). It only needs the final denominator’s inverse, and the squarings for that inverse can be shared with the query power. I handle the smallest primes and higher powers like \(13^2\) in scalar code.

A pedagogical Common Lisp implementation

This is a pedagogical implementation of the algorithm described in this post, including the \(M\)-\(3M\) pairing optimization and the prime-powers optimization. The code is otherwise not optimized; a proper implementation would be multithreaded and vectorized, including the aforementioned SIMD optimizations.

We start with some basic arithmetic utilities.

(defun odd-primes-through (limit)
  (let ((marked (make-array (1+ limit) :element-type 'bit
                                       :initial-element 0)))
    (loop :for p :from 3 :to limit :by 2
          :when (zerop (bit marked p))
            :collect p :and :do
              (loop :for m :from (* p p) :to limit :by (* 2 p)
                    :do (setf (bit marked m) 1)))))

(defun pow2-mod (e q)
  (loop :with r := 1
        :for n := (abs e) :then (ash n -1)
        ;; For odd q, (q+1)/2 is the inverse of 2.
        :for base := (if (minusp e) (/ (1+ q) 2) 2)
          :then (mod (* base base) q)
        :while (plusp n)
        :when (oddp n) :do (setf r (mod (* r base) q))
        :finally (return r)))

(defun inverse-mod (u q)
  ;; Euclid's algorithm, tracking a = x*u and b = y*u modulo q.
  (loop :with a := q :and b := (mod u q)
        :with x := 0 :and y := 1
        :until (zerop b)
        :do (multiple-value-bind (quotient remainder) (floor a b)
              (psetf a b
                     b remainder
                     x y
                     y (- x (* quotient y))))
        :finally (assert (= a 1))
                 (return (mod x q))))

Each triple below describes one power in the boxed formula: its exponent is shift - slope*k, and its sign flips every run terms.

;; Numerator terms from the boxed formula.
;;
;; Each (shift slope run) describes one of the four powers over 2*k + 1.
;; Its exponent is shift - slope*k; its sign starts positive and flips
;; every run terms. For example, (1 3 2) gives 2^(1 - 3*k) with signs
;; +,+,-,-,+,+,-,-,... starting at k = 0.
(defvar *pi-numerator-terms*
  '(( 1  3 2)
    (-1  5 2)
    (-1  6 1)
    (-4 10 1)))

(defun term-sign (k run)
  (if (evenp (floor k run)) 1 -1))

(defun last-head-denominator (d)
  (1+ (* 2 (floor (1+ d) 3))))

Next, we implement the paired-head function, which calculates the head using the \(M\)-\(3M\) optimization. For \(M=2k+1\), active-powers builds a short list of triples (s b w), each representing \(w\,2^{d+b-sk}\). If we pair \(M\) with \(3M\), the terms for \(M\) get a weight of three. The partner’s index is \(3k+1\), so its exponent becomes \(d+(\text{shift}-\text{slope})-3\,\text{slope}\,k\). Now both sets of powers are written in terms of the same \(k\).

(defun active-powers (d k pairedp)
  (let ((terms nil))
    (flet ((add-power (s b w)
             (when (>= (+ d b) (* s k))
               (push (list s b w) terms))))
      (loop :for (shift slope run) :in *pi-numerator-terms*
            :do (add-power slope shift (* (if pairedp 3 1) (term-sign k run)))
                (when pairedp
                  (add-power (* 3 slope) (- shift slope)
                             (term-sign (1+ (* 3 k)) run)))))
    ;; For these terms, descending slope gives ascending exponent.
    (sort terms #'> :key #'first)))

(defun paired-fraction (d m pairedp)
  (let ((k (floor m 2))
        (q (if pairedp (* 3 m) m)))
    (destructuring-bind ((s b w) &rest more) (active-powers d k pairedp)
      (loop :with r := (pow2-mod (- (+ d b) (* s k)) q)
            :with total := (* w r)
            :with x := (when more (pow2-mod k q))
            :for (next-s next-b weight) :in more
            :for factor := (ash (expt x (- s next-s)) (- next-b b))
            :do (setf r (mod (* r factor) q)
                      s next-s
                      b next-b)
                (incf total (* weight r))
            :finally (return (/ (mod total q) q))))))

(defun paired-head (d)
  (loop :with limit := (last-head-denominator d)
        :for m :from 1 :to limit :by 2
        :for coprimep := (not (zerop (mod m 3)))
        :when (or coprimep (zerop (mod m 9)))
          :sum (paired-fraction d m (and coprimep (<= (* 3 m) limit)))))

The factor in that loop is just the step from one exponent to the next: \(x^{s-s'}2^{b'-b}\), where \(x=2^k\bmod q\). If only one power is active, we never compute \(x\). If both 13 and 39 are active, the entire loop runs modulo 39 and ends with one division. paired-head then skips 39 when it reaches it; 9, on the other hand, is processed on its own.

Next, we implement the prime-head function, which calculates the head using the prime-powers optimization. For a particular prime power \(q=p^e\), visit the denominators \(qu\) for \(u=1,3,5,\ldots\), skipping multiples of \(p\). For instance, \(39=13\cdot3\) belongs in the group for 13, but \(169=13\cdot13\) belongs in the group for 169 instead. As \(u\) advances by two, \(k=(qu-1)/2\) advances by \(q\). That’s why we can update the unshifted power weight by a multiplication each time.

(defun group-coefficient (d p q)
  (loop :with first-k := (floor q 2)
        :for (shift slope run) :in *pi-numerator-terms*
        :for last-k := (floor (+ d shift) slope)
        :when (<= first-k last-k)
          :sum (loop :with count := (1+ (floor (- last-k first-k) q))
                     :with weight-period := (lcm (* 2 run)
                                                 (/ (1- p) (gcd slope (1- p))))
                     :with jump := (pow2-mod (- (* slope q)) q)
                     :for k :from first-k :by q
                     :for u :from 1 :by 2
                     :for weight := (pow2-mod (- shift (* slope first-k)) q)
                       :then (mod (* weight jump) q)
                     ;; Over q weight periods, opposite cofactors'
                     ;; inverses cancel modulo q.
                     :repeat (mod count (* q weight-period))
                     :unless (zerop (mod u p))
                       :sum (* (term-sign k run) weight (inverse-mod u q)))
          :into c
        :finally (return (mod c q))))

(defun prime-head (d)
  (let ((limit (last-head-denominator d)))
    (loop :for p :in (odd-primes-through limit)
          :sum (loop :for q := p :then (* q p) :while (<= q limit)
                     :sum (/ (mod (* (pow2-mod d q)
                                     (group-coefficient d p q))
                                  q)
                             q)))))

prime-head computes \(2^d\bmod q\) once per group. This version of group-coefficient also uses modular powers to initialize weight and jump, but not for every multiple of \(q\). The denominator 1 needs no group: its active terms are integers.

Finally, we implement the tail, which is the same regardless of optimization. If we stop a family when its exponent drops below \(-B\), the first omitted term has magnitude at most \(2^{-B-1}\) and each following term is at most one eighth as large. So \(4\cdot2^{-B}\) bounds the total error from all four tails. If that could change the last hex digit, we take a few more terms.

(defun tail-sum (d bits)
  (loop :for (shift slope run) :in *pi-numerator-terms*
        :for first-k := (max 0 (1+ (floor (+ d shift) slope)))
        :sum (loop :for k :from first-k
                   :for e := (- (+ d shift) (* slope k))
                   :while (>= e (- bits))
                   :sum (/ (* (term-sign k run) (expt 2 e)) (1+ (* 2 k))))))

(defun pi-hex-digits (skip &key (width 12) (head #'prime-head))
  (check-type skip (integer 0 *))
  (check-type width (integer 1 *))
  (let* ((d (* 4 skip))
         (scale (expt 16 width))
         (h (funcall head d)))
    (loop :for bits :from (+ (* 4 width) 8) :by 16
          :for value := (+ h (tail-sum d bits))
          :for radius := (* 4 (expt 2 (- bits)))
          :for lo := (floor (* scale (- value radius)))
          :for hi := (floor (* scale (+ value radius)))
          :when (= lo hi)
            :return (format nil "~v,'0X" width (mod lo scale)))))

skip counts hex digits after the point, not bits. :width defaults to 12 digits and :head defaults to #'prime-head. Use :head #'paired-head to select pairing:

CL-USER> (pi-hex-digits 100 :width 8 :head #'prime-head)
"29B7C97C"
CL-USER> (pi-hex-digits 100 :width 8 :head #'paired-head)
"29B7C97C"

  1. Craig-Wood’s implementation evaluates 21 fractions separately for every 30 bits of offset. ↩︎

  2. There’s a way to thin out the far end of the loop even more. At \(j=4m+3\), the real and imaginary parts of \((1+i)^j\) are opposites. Add the real part of each logarithm and the two slow powers cancel for \(N\equiv3\pmod4\). We still have to subtract the real logarithms we added, using series for \(\log(1+2^{-2})\), \(\log(1+2^{-3})\), and \(\log(1-2^{-4})\). That leaves half as many moduli above \(d/2\), at the cost of more streams of powers to juggle below it. ↩︎

  3. Thanks to Doug Coleman and Prajay Basu for sharing their explorations of this algorithm. ↩︎

Reactions
Sign in to react

Discussion

0 comments on Savant Gateway

This discussion is ours, not the publisher's. The thread is public. Sign in to post; the source's own comment count, when reported, appears in the details panel. One level of replies is supported.

Sign in to join the discussion.

No comments yet. Start the conversation.