一种更快的提取π的十六进制数字的算法
A faster algorithm for extracting hexadecimal digits of π

原始链接: https://www.stylewarning.com/posts/faster-digit-extraction/

这篇帖子介绍了一种基于欧拉级数的新的π十六进制数字提取算法,通过在分母间共享运算来减少模幂运算。它没有独立计算BBP型项,而是对齐奇分母,将四个余数合并到分母2k+1下,并利用小的2的幂间隙,从一个起始幂和步进2^k mod M推导出余数。它进一步将模数M与3M配对,使得两个分母上的八个幂共享两次模幂运算和一次除法。这产生约7d/27次除法和56d/135次完整模幂运算,相比之下Huvent为2d/3,每完整模幂运算约2.41比特,每次除法约3.86比特。一个AVX-512 IFMA实现提取12个十六进制数字的速度远快于Huvent,偏移量可达1万亿位,速度提升最高约62%。关键实现技巧包括蒙哥马利运算、模数配对、向量绝对值优化,以及按活跃幂批量处理模数。

黑客新闻 新帖 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 一种更快的提取π十六进制数字的算法 (stylewarning.com) 5分 由 vinhnx 1小时前 | 隐藏 | 过去 | 收藏 | 讨论 帮助 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请YC | 联系 搜索:
相关文章

原文

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. Even against Huvent’s eight-term formula, the savings at large offsets are about 61% fewer divisions and 38% fewer full modular exponentiations.

The key is a relationship among the four powers of two in this 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 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. As we will see, the gaps between them stay small multiples of \(k\) plus constants, so one starting power and the step \(2^k\bmod M\) let us reach the others by multiplication.

Even better, working modulo \(3M\) lets the same two exponentiations serve both \(M\) and \(3M\). Eight powers of two over two different denominators can share two full exponentiations and a single division. For every million hexadecimal places skipped, that saves about a million full exponentiations compared with Huvent, before any machine-specific optimization enters into it.

The BBP trick and formula convergence

To see where the savings come from, recall the BBP trick. To skip \(n\) hex digits, shift \(\pi\) left by \(d=4n\) bits and take the fractional part. For a term \(2^E/N\) with \(E\ge 0\), we only need \((2^E\bmod N)/N\) because the difference is an integer which doesn’t contribute to the fractional part. So even at \(d=4{,}000{,}000\) we never have to construct a four-million-bit numerator. The terms with negative exponents still count; they decay geometrically, so we can sum their tails directly, keeping enough guard bits to settle the last digit we want.

Last time, I counted the work by counting fractions. 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 feverishly tried 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 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. Craig-Wood used it to extract hexadecimal digits. In the original notation there are six rows:

\[ \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 straightforwardly as two sums:

\[ \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 what we’re dividing by. 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. We can collect terms this way for every odd denominator.

To derive the boxed formula directly, we can start with a multiplication of Gaussian integers: \((3-i)^2(7-i)=50(1-i)\). Taking complex arguments gives Hutton’s arctangent identity from the 18th century:

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

Bellard lists this identity as equation (7). His logarithm trick works on both angles: \(1-(1+i)/4=(3-i)/4\), and \(1-(1+i)/8=(7-i)/8\). So if we put

\[ I_u := \operatorname{Im}\!\left[-\log\!\left(1-\frac{1+i}{2^u}\right)\right] = \operatorname{Im}\sum_{j=1}^{\infty}\frac{(1+i)^j}{j\,2^{uj}}, \]

then \(I_2=\arctan(1/3)\), \(I_3=\arctan(1/7)\), and we want \(\pi=8I_2+4I_3\). Every time \(j\) goes up by four, \((1+i)^j/2^{uj}\) is multiplied by \(-4/2^{4u}\). That’s \(-1/64\) in the first sum and \(-1/1024\) in the second.

For an odd denominator \(N=2k+1\), the two contributions in each logarithm come from \(j=N\) and \(j=2N\). All further doublings give multiples of four, where \((1+i)^j\) is real and contributes nothing. At \(j=N\) the imaginary part of \((1+i)^N\) is \((-1)^{\lfloor k/2\rfloor}2^k\); at \(j=2N\) we’re looking at \((2i)^N=(-1)^k 2^N i\). At \(j=N\), the first logarithm multiplies the imaginary part by \(8/2^{2(2k+1)}\), giving the numerator term \((-1)^{\lfloor k/2\rfloor}2^{1-3k}\). Collect the other three contributions in the same way and we have 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\). That’s two exponentiations for the first \(d/5\) denominators and one for the remaining \(d/3-d/5\), or about \(8d/15\) altogether.

Two denominators for the price of one

There’s one more thing we can do with 13. Suppose we’re going to compute remainders modulo 39 anyway. A remainder modulo 39 is good modulo 13 too, and \(A/13+B/39=(3A+B)/39\), so we only need a single division by 39.

To avoid counting a denominator twice, we start a pair only at an odd \(M\) that isn’t divisible by three. If \(3M\) is in range, we handle it together with \(M\); otherwise we handle \(M\) alone. So 39 gets handled with 13, and we don’t also pair 39 with 117. Multiples of nine, like 117, get their own turn.

The two numerators can share the exponentiations, too. The index for \(M=2k+1\) is \(k\); for \(3M\) it’s \(3k+1\). For 13 and 39 those indices are 6 and 19: once we have \(2^6\bmod 39\), we get \(2^{19}\bmod 39\) just by cubing and doubling. In general, all eight exponents have the same \(d\), so their differences are small multiples of \(k\) plus constants. We compute just two powers modulo \(3M\): the smallest active power across the pair and the step \(2^k\). Multiplication gives us the rest. The largest exponent for \(3M\) is \(d-2-9k\), so it drops out near \(k=d/9\), before \(M\) stops needing the step near \(k=d/5\). Whenever there’s a partner, \(M\) would already need two exponentiations on its own.

In any nine consecutive odd denominators, three are divisible by three. One of those is divisible by nine and keeps its own turn, while the other two are absorbed into their smaller partners. That leaves seven trips through the loop instead of nine, 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.

Here is how the formulas compare in bits of offset per operation:

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 post135/56 ≈ 2.4127/7 ≈ 3.86

Notes on a high-performance implementation

I implemented both the algorithm of this post and Huvent using AVX-512 IFMA. Here’s how long each took to extract 12 hex digits on my computer.

Hex digits skippedThreadsHuvent (ms)This post (ms)% faster
1,000,00018.094.88+65.7%
100,000,0001962584+64.7%
1,000,000324.233.82+10.9%
100,000,0003264.442.4+51.8%
1,000,000,00032655410+59.9%
1,000,000,000,00032845,685520,907+62.3%

These are median times except at a trillion digits, where I timed each method once. The percentages use unrounded times: 62.3% faster in the last row means 38.4% less elapsed time.

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.

I originally went looking for a series with fewer fractions per bit. If you evaluate every fraction separately, Euler’s series actually needs more fractions per bit than Huvent’s, so it has been easy to pass over. Sharing the modular arithmetic across common and paired denominators is what makes it faster, and I suspect similar tricks apply to other BBP-type series.

联系我们 contact @ memedata.com