Attention is built on one function: every weight is \(e^{s_i}\), normalized (chapter 15, chapter 16). The paper [refinekv] analyses that function more than any other. Its error bound is made of two hyperbolic functions, \(\cosh \delta_C - 1\) and \(\tanh(\delta_C/2)\), of a cluster's logit spread \(\delta_C\), and its proofs (Appendix A.6) use exactly the facts collected here: \(e^{a+b} = e^a e^b\), the tangent and chord bounds of exp, and a handful of identities between cosh, sinh and tanh. This chapter defines exp by its one property, derives everything else from it, checks every identity numerically, and ends by computing exp the way a libm does.
Money at continuous interest, a population with no limits, the count of unprocessed requests that each spawn more: the rate of growth is proportional to the amount. With rate 1, the amount \(y(x)\) at time \(x\) satisfies
\[ y' = y, \qquad y(0) = 1. \]An equation for a function in terms of its derivative is a differential equation (chapter 6; this one is solved by separation of variables in section 6.2). It has exactly one solution, and that solution is the exponential function, \(\exp\).
A program can solve it without knowing anything else. Euler's method (section 6.6) steps forward with the current slope: from \(x\) to \(x + h\), \(y \leftarrow y + h \cdot y'(x) = y + h y = (1 + h) y\). With \(n\) steps of size \(h = 1/n\) from 0 to 1, \(y(1) \approx (1 + 1/n)^n\): the compound-interest sequence of section 1.5, whose limit is \(e\). So
\[ \exp(1) = e = \lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^n \approx 2.718281828. \]Run for \(n = 10\), 100 and 1000, the loop gives 2.5937, 2.7048 and 2.7169: \((1 + 1/n)^n\) exactly, since every step multiplies by \(1 + 1/n\), and an error near \(e/(2n)\), Euler's first-order error (section 6.6). Why only one solution: if \(y' = y\), then by the product and chain rules \((y(x) e^{-x})' = y' e^{-x} - y e^{-x} = 0\), so \(y(x) e^{-x}\) is constant (section 2.8), and \(y(0) = 1\) fixes the constant. The same argument shows that \(y' = k y\) has the solutions \(y = y(0)\, e^{kx}\): growth at rate \(k\), or decay if \(k < 0\).
Theorem (addition law). For all real \(a\) and \(b\),
\[ \exp(a + b) = \exp(a)\, \exp(b). \]Why: fix \(a\). As functions of \(x\), both \(\exp(a + x)\) and \(\exp(a) \exp(x)\) have derivative equal to themselves and value \(\exp(a)\) at \(x = 0\). The uniqueness argument of section 4.1 (with \(y(0) = \exp(a)\)) says they are the same function. Everything else follows:
The law turns sums in the exponent into products of weights. That is the first step of the paper's analysis. A token's logit is \(s_i = q^\top k_i / \sqrt{d}\). Write the key as the cluster's mean key plus a deviation, \(k_i = \bar{k}_C + (k_i - \bar{k}_C)\). The dot product is linear (section 8.3), so
\[ \exp\!\left(\frac{q^\top k_i}{\sqrt{d}}\right) = \exp\!\left(\frac{q^\top \bar{k}_C}{\sqrt{d}}\right) \exp\!\left(\frac{q^\top (k_i - \bar{k}_C)}{\sqrt{d}}\right), \quad\text{that is}\quad e^{s_i} = e^{s_C}\, e^{x_i}, \]where \(s_C = q^\top \bar{k}_C / \sqrt{d}\) is the representative's logit and \(x_i = s_i - s_C\) the token's deviation from it. Sum over the cluster:
\[ z_C = \sum_{i \in C} e^{s_i} = |C|\, e^{s_C} \cdot \underbrace{\frac{1}{|C|} \sum_{i \in C} e^{x_i}}_{m_C} = \hat{z}_C \, m_C. \]The cluster's true mass \(z_C\) is the mass the representative is credited with, \(\hat{z}_C = |C| e^{s_C}\), times a correction \(m_C\): the average of \(e^{x_i}\). (Also \(\hat{z}_C = e^{s_C + \ln |C|}\): the representative acts as one token with logit \(s_C + \ln |C|\), as the paper puts it; \(\ln\) is next section.) If all tokens' logits equalled the representative's, every \(x_i = 0\) and \(m_C = 1\): no error. The whole question of how good the cheap attention is becomes how far \(m_C\) is from 1, which depends only on the deviations \(x_i\), and they lie in \([-\delta_C, \delta_C]\). Section 4.4 and section 4.6 bound it. One more fact makes those bounds work: the \(x_i\) average to zero, because \(\frac{1}{|C|}\sum_i q^\top k_i = q^\top \bar{k}_C\).
A numerical example: 16 keys in \(d = 64\) dimensions scattered around a common centre, and a random query. Then \(s_C = -0.4537\), \(\hat{z}_C = 16 e^{s_C} = 10.1645\), the true mass is \(z_C = 10.2405\), and \(m_C = 1.00748\); \(\hat{z}_C m_C\) reproduces \(z_C\) to all printed digits. The spread is \(\delta_C = 0.3017\), and the correction is far inside the bound \(\cosh \delta_C = 1.0459\) that section 4.6 proves. The same law gives softmax's shift invariance: multiplying every \(e^{s_i}\) by \(e^{-c}\) changes no ratio, which is what makes the max trick of section 15.2 legal.
In the machine. \(e^x\) overflows a double for \(x > 709.78\) (\(\ln\) of the largest double) and underflows to 0 below about \(-745\). Logits rarely get there, but their exponentials in float or fp16 overflow far sooner (fp16 above \(x \approx 11\)): one more reason softmax subtracts the maximum first (section 14.7).
\(e^x\) is increasing (section 4.4) and takes every positive value, so it has an inverse on \((0, \infty)\): the natural logarithm, \(\ln y = x\) exactly when \(e^x = y\). The graph of \(\ln\) is the graph of \(\exp\) mirrored in the line \(y = x\).
Each law of exp becomes a law of ln, read backwards:
\[ \begin{aligned} \ln(ab) &= \ln a + \ln b, & \ln\frac{a}{b} &= \ln a - \ln b, & \ln(a^p) &= p \ln a, \\ \ln 1 &= 0, & \ln e &= 1. \end{aligned} \]For the first: \(e^{\ln a + \ln b} = e^{\ln a} e^{\ln b} = ab\), so \(\ln a + \ln b\) is the number whose exp is \(ab\). Logs turn products into sums: a product of a thousand probabilities underflows, the sum of their logs does not. Other bases go through \(e\): \(a^x = e^{x \ln a}\) and \(\log_2 x = \ln x / \ln 2\).
Derivative. If \(y = \ln x\) then \(x = e^y\); differentiate in \(x\) with the chain rule: \(1 = e^y\, y'\), so \(y' = 1/e^y\):
\[ (\ln x)' = \frac{1}{x}, \qquad x > 0. \]Log-sum-exp. The log of a sum of exponentials, \(\ln \sum_i e^{s_i}\), is the log of softmax's denominator. Computed as written it overflows as soon as one \(s_i\) passes 709. Taking the largest, \(m = \max_i s_i\), out with the addition law fixes it: \(\ln \sum_i e^{s_i} = m + \ln \sum_i e^{s_i - m}\), where every exponent is now \(\le 0\) (section 15.3; its convexity is in section 11.5, its gradient, softmax, in section 7.6).
In doubles, \(\ln(e^{1000} + e^{999})\) as written is inf; with the maximum taken out it is \(1000 + \ln(1 + e^{-1}) = 1000.3132616875\).
In the machine. The laws hold in floating point only up to rounding, and exp amplifies one kind. Checked over a million random \(a, b \in [-300, 300]\), \(e^{a+b}\) and \(e^a e^b\) differ by up to \(5.7 \times 10^{-14}\) relative: not a failure of the law, but of the input, since \(a + b\) is rounded (to within half an ulp of 600, which is \(5.7 \times 10^{-14}\)) before exp sees it, and \((e^x)' = e^x\) means an absolute input error \(\Delta\) becomes a relative output error \(\Delta\). The log laws hold to \(2 \times 10^{-15}\) absolute.
In the machine. A double already stores a base-2 logarithm: \(x = f \cdot 2^k\) with \(f \in [1, 2)\), so \(\log_2 x = k + \log_2 f\), and frexp extracts \(k\) for free. A libm's log computes only \(\ln f\) on a short interval with a polynomial and adds \(k \ln 2\): the mirror image of the range reduction for exp in section 4.7.
The bounds in the paper are built from a few facts about \(e^x\). All follow from the derivative.
Facts.
1. \(e^x > 0\) for all \(x\) (section 4.2).
2. \(e^x\) is strictly increasing: \(a < b \Rightarrow e^a < e^b\). Its derivative \(e^x\) is positive (section 2.8).
3. \(e^x \ge 1 + x\) for all \(x\), with equality only at \(x = 0\). The tangent at 0 lies below the curve.
4. If \(|x| \le \delta\) then \(e^{-\delta} \le e^x \le e^{\delta}\). (From 2.)
For fact 3, let \(g(x) = e^x - 1 - x\). Then \(g'(x) = e^x - 1\) is negative for \(x < 0\) and positive for \(x > 0\), so \(g\) falls to its minimum at 0 and rises after (section 2.7); \(g(0) = 0\), so \(g \ge 0\). Behind it is convexity: \((e^x)'' = e^x > 0\), and a convex function lies above all its tangents (section 11.2). Putting \(x = \ln(1 + t)\) into fact 3 gives its twin, \(\ln(1 + t) \le t\) for \(t > -1\).
Fact 3 gives the lower half of the paper's mass bound in one line. The deviations \(x_i\) in a cluster average to 0 (section 4.2), so
\[ m_C = \frac{1}{|C|} \sum_{i \in C} e^{x_i} \ge \frac{1}{|C|} \sum_{i \in C} (1 + x_i) = 1 + 0 = 1. \]The representative never over-credits its cluster: \(\hat{z}_C \le z_C\). Fact 4 gives a crude two-sided bound, \(e^{-\delta_C} \le m_C \le e^{\delta_C}\), and the ratio bound the paper uses for weights inside a cluster: \(e^{x_i} / e^{x_j} = e^{x_i - x_j} \le e^{2\delta_C}\). The chord gives a far better upper bound, \(\cosh \delta_C\) (section 4.6). (Facts 1 to 4 and \(\ln(1+t) \le t\) were checked on a grid of six million points in \([-30, 30]\): the smallest gap \(e^x - (1 + x)\) is exactly 0, at \(x = 0\).)
Split \(e^x\) into its even and odd parts, the way any function splits as \(f(x) = \frac{f(x) + f(-x)}{2} + \frac{f(x) - f(-x)}{2}\):
Definition. The hyperbolic cosine, sine and tangent are
\[ \cosh x = \frac{e^x + e^{-x}}{2}, \qquad \sinh x = \frac{e^x - e^{-x}}{2}, \qquad \tanh x = \frac{\sinh x}{\cosh x} = \frac{e^x - e^{-x}}{e^x + e^{-x}}. \]So \(e^x = \cosh x + \sinh x\) and \(e^{-x} = \cosh x - \sinh x\). The names come from the identity \(\cosh^2 - \sinh^2 = 1\) of section 4.6: the point \((\cosh t, \sinh t)\) runs along the hyperbola \(X^2 - Y^2 = 1\) as \((\cos t, \sin t)\) runs around the circle. Read \(\cosh \delta\) as what it is in the paper: the average of \(e^{\delta}\) and \(e^{-\delta}\), the chord's height at the middle in figure 4.2.
What the graphs show, and why:
The last is the quotient rule plus the identity of section 4.6. Since \(0 < 1 - \tanh^2 \le 1\), tanh is increasing with slope at most 1: \(|\tanh x - \tanh y| \le |x - y|\) by the slope bound of section 2.8. All of these were checked numerically (section 4.6).
In the machine. \(1 - \tanh x\) is about \(2e^{-2x}\), which drops below the gap under 1 (\(2^{-53}\)) near \(x = 19\): tanh(20) is exactly 1.0 in doubles, though mathematically \(|\tanh| < 1\). Code that relies on \(\tanh < 1\), say to divide by \(1 - \tanh^2\), must not rely on it in floating point.
These are the identities the paper's appendix uses, each with its derivation. Write \(E = e^x\), so \(e^{-x} = 1/E\).
The hyperbola. \(\cosh^2 x - \sinh^2 x = (\cosh x + \sinh x)(\cosh x - \sinh x) = e^x e^{-x} = 1\).
Half-angle for cosh. \(2\sinh^2(x/2) = 2 \left(\frac{e^{x/2} - e^{-x/2}}{2}\right)^2 = \frac{e^x - 2 + e^{-x}}{2} = \cosh x - 1\). So
\[ \cosh x - 1 = 2 \sinh^2 \frac{x}{2} \ge 0. \]The right side is the one to compute with for small \(x\): \(\cosh x - 1\) cancels, as \(1 - \cos x\) did in section 1.3.
Half-angle for tanh. Three forms, all used:
\[ \tanh\frac{x}{2} = \frac{e^x - 1}{e^x + 1} = \frac{\sinh x}{1 + \cosh x} = \frac{\cosh x - 1}{\sinh x} \quad (x \ne 0 \text{ for the last}). \]Derivation. Multiply top and bottom of \(\tanh\frac{x}{2} = \frac{e^{x/2} - e^{-x/2}}{e^{x/2} + e^{-x/2}}\) by \(e^{x/2}\): that is the first form, \(\frac{E - 1}{E + 1}\). Multiply it top and bottom by \(E + 1\):
\[ \frac{(E - 1)(E + 1)}{(E + 1)^2} = \frac{E^2 - 1}{E^2 + 2E + 1} = \frac{E - 1/E}{E + 2 + 1/E} = \frac{2 \sinh x}{2\cosh x + 2} = \frac{\sinh x}{1 + \cosh x}, \]dividing by \(E\) in the third step. For the last form, multiply top and bottom by \(\cosh x - 1\) and use the hyperbola: \(\frac{\sinh x (\cosh x - 1)}{\cosh^2 x - 1} = \frac{\sinh x (\cosh x - 1)}{\sinh^2 x} = \frac{\cosh x - 1}{\sinh x}\). The paper's tanh lemma ends with the first form: a ratio bound \(\frac{\sqrt{R} - 1}{\sqrt{R} + 1}\) with \(\sqrt{R} \le e^{\delta}\) is recognized as \(\tanh(\delta/2)\) (section 19.5).
tanh is below the identity. For \(x \ge 0\), \(\tanh x \le x\). Let \(g(x) = x - \tanh x\): \(g(0) = 0\) and \(g'(x) = 1 - (1 - \tanh^2 x) = \tanh^2 x \ge 0\), so \(g\) never decreases. By oddness, \(|\tanh x| \le |x|\) for all \(x\).
The logistic function is a shifted, scaled tanh:
\[ \sigma(x) = \frac{1}{1 + e^{-x}} = \frac{e^x}{e^x + 1} = \frac{1}{2}\left(1 + \frac{e^x - 1}{e^x + 1}\right) = \frac{1 + \tanh(x/2)}{2}. \]With two tokens, softmax's first weight is \(\frac{e^{s_1}}{e^{s_1} + e^{s_2}} = \sigma(s_1 - s_2)\): the logistic function is a two-way softmax (section 12.6).
Small \(\delta\). The paper's bound has a term in \(\cosh \delta_C - 1\) (mass) and one in \(\tanh(\delta_C/2)\) (values). For small spread,
\[ \cosh \delta - 1 \approx \frac{\delta^2}{2}, \qquad \tanh\frac{\delta}{2} \approx \frac{\delta}{2}, \]with \(\cosh \delta - 1 \ge \delta^2/2\) always (the series \(\cosh \delta - 1 = \frac{\delta^2}{2!} + \frac{\delta^4}{4!} + \cdots\) has only positive terms, section 5.4) and \(\tanh(\delta/2) \le \delta/2\) (just shown). The mass error is second order in the spread, the value error first order. How good the approximations are:
| \(\delta\) | \(\cosh \delta - 1\) | \(\delta^2/2\) | ratio | \(\tanh(\delta/2)\) | \(\delta/2\) | ratio |
|---|---|---|---|---|---|---|
| 2 | 2.7622 | 2 | 1.3811 | 0.76159 | 1 | 0.7616 |
| 0.2 | 0.020067 | 0.02 | 1.0033 | 0.099668 | 0.1 | 0.9967 |
| 0.02 | 0.00020001 | 0.0002 | 1.00003 | 0.0099997 | 0.01 | 0.99997 |
At \(\delta = 0.02\) both are good to 0.003%; at \(\delta = 2\) they are not. The ratios are \(1 + \delta^2/12\) and \(1 - \delta^2/12\) to leading order (section 5.4). Every identity of this section and the last, and the derivatives, were checked numerically on \([-10, 10]\): all hold to within a few units of \(10^{-16}\), except where an algebraically equal form cancels. \((\cosh x - 1)/\sinh x\) is off by \(7 \times 10^{-14}\) near 0, while \(\sinh x / (1 + \cosh x)\), the same number, is exact to the last bit: choose the form without the subtraction.
Lemma (the paper's Lemma A.2, with the lower bound of section 4.4 added). If \(x_1, \dots, x_n\) lie in \([-\delta, \delta]\) and their average is 0, then
\[ 1 \le \frac{1}{n} \sum_{i=1}^{n} e^{x_i} \le \cosh \delta. \]The left inequality is section 4.4. For the right one, figure 4.2 is the proof: \(e^x\) on \([-\delta, \delta]\) lies below its chord, \(e^x \le \frac{\delta + x}{2\delta} e^{\delta} + \frac{\delta - x}{2\delta} e^{-\delta}\) (convexity, section 11.6). Average this over the \(x_i\): the chord is linear in \(x\), so its average is its value at the average \(x\), which is 0, and that value is \(\frac{e^{\delta} + e^{-\delta}}{2} = \cosh \delta\). Equality needs every \(x_i\) at an end of the interval, half of them at each. Applied to a cluster: \(1 \le m_C \le \cosh \delta_C\), so the mass correction is off by at most \(\cosh \delta_C - 1 \approx \delta_C^2/2\).
The bound is a worst case over all sets of numbers, which no test can enumerate, but a test can try hard to break it. The program draws 200000 random sets:
#include <math.h>
#include <stdint.h>
#include <stdio.h>
static uint64_t st = 0x2545F4914F6CDD1DULL;
static double rnd(void) /* uniform in [0, 1) */
{
st ^= st << 13; st ^= st >> 7; st ^= st << 17;
return (st >> 11) * 0x1p-53;
}
int main(void)
{
/* x_1..x_n in [-delta, delta] with mean 0: is mean(e^{x_i}) <= cosh(delta)? */
double worst = 0, least = INFINITY;
for (int t = 0; t < 200000; t++) {
int n = 3 + (int)(rnd() * 29);
double x[32], mean = 0, big = 0, delta = 3 * rnd() + 1e-3;
for (int i = 0; i < n; i++) {
x[i] = rnd() < 0.5 ? rnd() : -rnd() * rnd(); /* lopsided on purpose */
mean += x[i] / n;
}
for (int i = 0; i < n; i++) {
x[i] -= mean;
if (fabs(x[i]) > big) big = fabs(x[i]);
}
double m = 0;
for (int i = 0; i < n; i++)
m += exp(x[i] * delta / big) / n; /* rescaled: max |x_i| = delta */
if (m / cosh(delta) > worst) worst = m / cosh(delta);
if (m < least) least = m;
}
printf("largest mean(e^x) / cosh(delta) = %.9f\n", worst);
printf("smallest mean(e^x) = %.9f\n", least);
double d = 1.5; /* half at -delta, half at +delta */
printf("x = +-1.5: mean(e^x) = %.6f cosh(1.5) = %.6f\n", (exp(d) + exp(-d)) / 2, cosh(d));
return 0;
}
largest mean(e^x) / cosh(delta) = 0.999999731 smallest mean(e^x) = 1.000000121 x = +-1.5: mean(e^x) = 2.352410 cosh(1.5) = 2.352410
How it maps to the lemma. Each trial picks a size \(n \in [3, 31]\) and a spread \(\delta \in (0, 3]\). The raw values are drawn lopsided on purpose (positive ones uniform on \([0, 1)\), negative ones the product of two uniforms, so piled up near 0): the lemma has no symmetry assumption, so the test should not supply one. Then the two hypotheses are imposed exactly. Subtracting mean makes \(\frac{1}{n}\sum x_i = 0\); multiplying by delta / big, where big is \(\max_i |x_i|\), puts the extreme point exactly at \(\pm\delta\) and the rest inside \([-\delta, \delta]\); scaling does not disturb the zero mean. m is \(\frac{1}{n}\sum e^{x_i}\), the paper's \(m_C\). The program keeps the largest ratio \(m / \cosh\delta\), which the lemma says is at most 1, and the smallest \(m\), which section 4.4 says is at least 1. The last line is the equality case.
No set beats \(\cosh \delta\), none falls below 1, and the two-point set \(\pm\delta\) attains the bound. (Sets with \(n = 2\) are left out of the random trials for that reason: after centring and scaling they are always \(\pm\delta\).) The bound is tight: it cannot be improved without knowing more about the \(x_i\) than their range and mean.
A libm's exp uses three ideas [tang-exp] [muller].
1. Range reduction. Write \(x = k \ln 2 + r\) with \(k = \operatorname{round}(x / \ln 2)\), an integer, so that \(|r| \le \tfrac12 \ln 2 \approx 0.347\). Then \(e^x = 2^k e^r\), by the addition law.
2. A polynomial for \(e^r\) on that short interval. The Taylor polynomial \(1 + r + r^2/2! + \dots + r^{13}/13!\) (section 5.4) leaves out terms starting at \(r^{14}/14! \le 4 \times 10^{-18}\), well below a double's \(1.1 \times 10^{-16}\). Evaluate it in nested (Horner) form: 13 multiply-adds.
3. Scaling by \(2^k\) is free: add \(k\) to the exponent field. That is ldexp.
One subtlety is in step 1. \(k \ln 2\) must be subtracted from \(x\) almost exactly, or \(r\) inherits a relative error that the polynomial cannot remove. The trick (Cody and Waite's) splits \(\ln 2\) into a high part with its low 32 bits zero, so that \(k \cdot\)LN2_HI is exact for any \(|k| < 2^{20}\), and a low part for the rest. Real libms go one step further: they reduce \(r\) to \(|r| \le \ln 2 / 64\) with a table of the 32 values \(2^{j/32}\), so a polynomial of about degree 5 suffices [tang-exp]. The x87 has the same pieces in hardware: F2XM1 computes \(2^x - 1\) on \([-1, 1]\) and FSCALE multiplies by a power of 2 [intel-sdm].
The program measures the error in units in the last place (ulp, section 14.2) over 14 million points in \([-700, 700]\), against expl, which works in the x87's 64-bit significand and serves as the exact answer:
#include <math.h>
#include <stdio.h>
static const double LN2_HI = 6.93147180369123816490e-01; /* low 32 bits zero: k*LN2_HI is exact */
static const double LN2_LO = 1.90821492927058770002e-10; /* ln 2 - LN2_HI */
static const double LOG2E = 1.44269504088896338700e+00;
static double my_exp(double x) /* for |x| <= 700 */
{
double k = nearbyint(x * LOG2E); /* x = k ln 2 + r */
double r = (x - k * LN2_HI) - k * LN2_LO; /* |r| <= ln2/2, about 0.347 */
double p = 1; /* 1 + r(1 + r/2(1 + r/3(... (1 + r/13)))) */
for (int n = 13; n >= 1; n--)
p = 1 + p * r / n;
return ldexp(p, (int)k); /* times 2^k: add k to the exponent */
}
static double ulps(double y, long double ref) /* error in units of the last place */
{
return (double)(fabsl(y - ref) / ldexpl(1, ilogbl(ref) - 52));
}
int main(void)
{
double mine = 0, lib = 0, at = 0;
for (long i = 0; i <= 14000000; i++) {
double x = -700 + i * 1e-4 + 1e-9 * (i % 7);
long double ref = expl(x); /* 64-bit significand reference */
double e1 = ulps(my_exp(x), ref), e2 = ulps(exp(x), ref);
if (e1 > mine) { mine = e1; at = x; }
if (e2 > lib) lib = e2;
}
printf("my_exp: max error %.3f ulp (at x = %.4f)\n", mine, at);
printf("libm : max error %.3f ulp\n", lib);
printf("my_exp(1) = %.17g\nexp(1) = %.17g\n", my_exp(1), exp(1));
return 0;
}
my_exp: max error 1.161 ulp (at x = -97.3840) libm : max error 0.899 ulp my_exp(1) = 2.7182818284590455 exp(1) = 2.7182818284590455
Printed on FreeBSD 15.1 on amd64 (Core i5-9400), clang 19. It depends on the machine: elsewhere the timings, the random numbers or the last digits differ.
How it maps to the method. k = nearbyint(x * LOG2E) is \(k = \operatorname{round}(x/\ln 2)\), computed as a multiplication by \(\log_2 e = 1/\ln 2\) because a multiply is cheaper than a divide and only the nearest integer is needed. r = (x - k*LN2_HI) - k*LN2_LO is \(r = x - k \ln 2\) in Cody–Waite form: the product k*LN2_HI is exact and so is its subtraction from \(x\) (two nearly equal numbers, so the result fits), which leaves rounding only in the tiny correction term. The loop evaluates the degree-13 Taylor polynomial in nested form, \(1 + r(1 + \tfrac{r}{2}(1 + \tfrac{r}{3}(\cdots(1 + \tfrac{r}{13}))))\), from the inside out: Horner's rule with the factorials folded in, 13 steps, no power or factorial ever formed. ldexp(p, k) is the multiplication by \(2^k\). For the measurement, ulps divides the error by the spacing of doubles at the true value, \(2^{e - 52}\) for a value in \([2^e, 2^{e+1})\); the sample points step by \(10^{-4}\) with a small irregular offset so that they do not all land on the same few values of \(r\).
A short loop gets within 1.2 ulp everywhere; the system libm (FreeBSD's) stays under 0.9. The difference is in the details: our loop rounds at each of its 13 steps, including a division, while a libm uses minimax coefficients (section 5.6), fewer steps on a smaller \(r\), and adds the last, largest term with care. A production version also handles overflow, underflow, NaN and infinity before reducing.
Take \(\ln\): \(x \ln 2 = \ln 10\), so \(x = \ln 10 / \ln 2 \approx 3.321928\).
\(e^{s_i - c} = e^{s_i} e^{-c}\) by the addition law; the common factor \(e^{-c}\) comes out of the sum and cancels. Numerically, with \(c = 7.25\), both sides agree to 15 digits.
\(\left(\frac{\sinh}{\cosh}\right)' = \frac{\cosh \cdot \cosh - \sinh \cdot \sinh}{\cosh^2} = \frac{1}{\cosh^2} = \frac{\cosh^2 - \sinh^2}{\cosh^2} = 1 - \tanh^2\).
Divide top and bottom of \(\frac{e^{s_1}}{e^{s_1} + e^{s_2}}\) by \(e^{s_1}\): \(\frac{1}{1 + e^{-(s_1 - s_2)}} = \sigma(s_1 - s_2)\), and section 4.6 rewrites \(\sigma\) with tanh.
\((e^{-1} + 2 e^{1/2})/3 \approx 1.2218 < \cosh 1 \approx 1.5431\). The bound is attained only when every point is at an end of the interval; the two points at \(\tfrac12\) sit strictly below the chord.
\(\frac{e^{0.2} - 1}{e^{0.2} + 1} = \tanh 0.1 \approx 0.099668\), so the bound is \(2 \tanh 0.1 \approx 0.1993\), just under \(\delta = 0.2\), as \(\tanh(\delta/2) \le \delta/2\) promises.
my_exp round \(x/\ln 2\) to the nearest integer rather than truncating it? How many more Taylor terms would truncation need?
Rounding gives \(|r| \le \ln 2 / 2\); truncation gives \(r \in [0, \ln 2)\) (for \(x \ge 0\)). The first omitted term must be below about \(10^{-17}\): \((\ln 2/2)^{14}/14! \approx 4 \times 10^{-18}\), but \((\ln 2)^{n}/n!\) gets there only at \(n = 17\) (\(5.5 \times 10^{-18}\)). Truncation costs three more multiply-adds per call.
F2XM1 and FSCALE.