15.6 Polynomial approximation and range reduction: expf in C
Every softmax in a language model exponentiates its logits: the sampler once per token, attention once per query and key. In AI Engineering those loops move into C, in Softmax in C: three-pass and online two-pass, FlashAttention forward in C, and the SiLU of Elementwise kernels in C, which is . Each of them calls an exponential per element. The C library’s expf is correct, but it is opaque, its speed and accuracy differ between macOS and Linux (which breaks bitwise reproducibility between two CI runners), and it cannot be inlined into a vector loop.
Concepts from other sections (12)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0 in AI Engineering
- SiLU (swish): , the gate inside SwiGLU. Read more: 7.3 Activation Functions and Their Derivatives
- Subnormal: a value with exponent field 0, no implicit leading 1, and a fixed exponent , filling the gap between zero and the smallest normal. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- Taylor polynomial: the degree- polynomial whose value and first derivatives at a point match those of . Read more: 8.1 Taylor series, remainder bounds, and range reduction
- undefined behavior: an operation the C standard gives no meaning to, which the compiler assumes never happens. Read more: 1.3 C: memory, pointers, structs, headers, and the C11 toolchain in Programming and Algorithms
- ties to even: rounding a value exactly halfway between two representable numbers to the one with an even last bit. Read more: 23.2 Candle model runner (Llama + bigram, int4), Rust KV cache, sampler and PCG32 in AI Engineering
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Differential test: a check that two implementations of the same contract agree on generated inputs. Read more: 3.3 Oracles, golden and differential tests, gradcheck as a test in Software Engineering
- Tolerance budget: a test allowance that sums every deliberate perturbation and the rounding bound, and nothing else. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- online softmax: computing the maximum and the normalizer in one read by rescaling the running sum whenever the maximum grows. Read more: 22.4 Softmax in C: three-pass and online two-pass in AI Engineering
- Block table: the per-sequence list of KV block ids, one per 16 tokens. Read more: 15.1 A growable array in Programming and Algorithms
- score scale: the factor , by default , that keeps score variance at 1 whatever the width. Read more: 11.1 Scaled dot-product attention (forward and backward) in AI Engineering
The algorithm is already derived: exp_range_reduced in Taylor series, remainder bounds, and range reduction computes it in float64. This optional section ports it to float32 C with an accuracy contract in ulps, and handles the edges that a float64 prototype never meets: overflow at 88.72, underflow below , , and NaN. You will see how range reduction shrinks an infinite domain to a tiny interval exactly, why the subtraction that performs it must be split in two, how to choose a polynomial degree from a remainder bound, and how to scale the result by when runs past both ends of the exponent range.
Besides the Taylor chapter, you need Horner’s rule from Polynomials, Horner’s rule, and stable quadratic roots, exponent fields and subnormals from IEEE 754 anatomy, ulps, and round to nearest even, and the runtime support of C runtime support and an arena allocator with marks. The solution, expf.c (tl_expf, tl_exp_f32, and the helper pow2i), is a standalone C file built under ASan and UBSan. Its interface is in numerics.h, under the rules of c/ABI.md.
Learning objectives
- Reduce any float32 input to with , and explain why multiplying by is free.
- Use the Cody and Waite split of to compute without cancellation error.
- Choose a Taylor polynomial degree from its remainder bound and evaluate it with Horner’s rule.
- Apply for without overflow or undefined behavior, and handle NaN and the overflow and underflow edges exactly.
The notation
Section titled “The notation”| Symbol | Meaning | Type / shape |
|---|---|---|
| the input | float | |
| the integer nearest (ties to even) | int, in range | |
| the reduced argument | float, | |
| the polynomial approximating | float | |
| split: , | float constants | |
| the remainder of the degree-7 Taylor polynomial | ||
| the spacing of float32 values at |
Range reduction
Section titled “Range reduction”is defined everywhere, but a polynomial is accurate only near its center. The identity moves any input into a small interval: write , so
Choosing puts in . Multiplying by is free in binary floating point: (for ) is the float with exponent field and mantissa 0, and multiplying by it changes only the exponent of the result, so it is exact whenever the result stays normal.
Computing without losing it
Section titled “Computing rrr without losing it”The reduction itself hides a trap. subtracts two nearly equal numbers when is large: at , and . In float32, has an error of about , which is a relative error of in and therefore in the result: a hundred ulps.
Cody and Waite’s fix is to split with having few significant bits. has 9 significant bits and has 8, so fits in 17 bits and is exact in float32. is then exact too, because the two are within a factor of 2 of each other (Sterbenz’s lemma). The remaining is tiny, so its rounding error is tiny:
The polynomial
Section titled “The polynomial”With confined to a small interval, a polynomial can do the rest. Taylor’s theorem for at 0 with degree gives with . On and relative to , the two candidate degrees compare like this:
| Degree | Relative remainder bound | In float32 ulps of the result |
|---|---|---|
| 6 | about 3: too many | |
| 7 | about 0.1: rounding dominates |
Evaluate it with Horner’s rule: , seven multiply-adds from the innermost coefficient out. Each step rounds once, and the sum of those roundings plus the reduction is what an accuracy check measures: 1.21 ulp at worst for the solution.
Note: A minimax polynomial, fitted to minimize the worst error on the interval instead of matching derivatives at 0, gets the same accuracy at degree 5. That is what production libraries ship; see the end of the section.
Scaling by at the edges
Section titled “Scaling by 2k2^k2k at the edges”The last step, multiplying by , is only free in the middle of the range. The largest float is just below , so overflows for . The largest float below that is 0x1.62e42ep+6 , where : one past the largest exponent, since is not a float. Below the result is subnormal, and below it rounds to 0, where reaches .
Both ends fall outside , so apply as with (C rounds toward zero) and , both in . The first product is exact and the second rounds once, even into the subnormal range.
The special values come first. NaN returns NaN (converting NaN to int is undefined behavior in C, and UBSan aborts on it), returns , and (and ) returns .
Working it by hand
Section titled “Working it by hand”Run through every stage:
| Step | Computation | Value |
|---|---|---|
| , nearest integer | 1 | |
| (exact) | 0.306640625 | |
| 0.30685282 | ||
| Horner | ; ; ; ; ; ; ; | |
| scale | , : | 2.7182817 |
, and the float32 nearest to it is 2.7182817: the kernel is exact here. With : , , , result 0.36787945. With : , , , result 22026.465. These become the hand-worked test cases.
Designing the API
Section titled “Designing the API”/* tinyllm/numerics.h, expf section */float tl_expf(float x); /* within 2 ulp where e^x is normal; > 88.7228317 -> +inf; -inf -> +0; NaN -> NaN */void tl_exp_f32(const float *x, float *y, int64_t n); /* elementwise; y == x allowed */The solution writes pow2i(k) (the float from its bit pattern, for ) as a static helper. It keeps #pragma STDC FP_CONTRACT OFF over the Horner steps, so the compiler does not fuse them: a fused multiply-add is more accurate, but whether one is used differs between compilers and machines.
Building it step by step
Section titled “Building it step by step”Six decisions shape the code. First, answer the specials before any integer conversion: NaN, overflow, and underflow are decided by comparisons on , and doing them first keeps (int) away from NaN and , where the conversion is undefined behavior. Second, reduce with the nearest integer: puts in , while truncation would let reach , where the degree-7 polynomial is 20 ulp off. Third, subtract in two parts, so that and are exact and only the small rounds. Fourth, pick the degree from the remainder table: on , degree 7 leaves about 0.1 ulp of truncation and degree 6 about 3 ulp. Taylor coefficients are used because the remainder bound is provable by hand. Fifth, evaluate with Horner, unfused: seven multiply-adds, innermost first, each rounding once, with FP_CONTRACT OFF keeping the result identical across compilers. Sixth, scale by in two exact halves, since overflows the normal exponent range at both ends; with , each a valid normal float built from its bit pattern.
The constants and the power-of-two helper come first:
#pragma STDC FP_CONTRACT OFF
#define TL_EXP_HI 0x1.62e42ep+6f /* 88.7228317: largest x with e^x finite */#define TL_EXP_LO -0x1.9fe368p+6f /* -103.972076: below this e^x rounds to 0 */#define TL_LOG2E 0x1.715476p+0f /* 1 / ln 2 */#define TL_LN2_HI 0.693359375f /* 355 / 512: 9 significant bits */#define TL_LN2_LO -2.12194440e-4f /* ln 2 - TL_LN2_HI */
/* 2^k for -126 <= k <= 127: exponent field k + 127, mantissa 0. */static float pow2i(int k) { uint32_t u = (uint32_t)(k + 127) << 23; float f; memcpy(&f, &u, sizeof f); /* the defined way to reinterpret bits */ return f;}The constants are written in hex-float form where the exact bit pattern matters. TL_EXP_HI is the largest float whose exponential is finite, so the overflow test is x > TL_EXP_HI, not >=. TL_LN2_HI is , exactly representable with 9 significant bits; TL_LN2_LO is negative because is slightly larger than . pow2i only ever receives , so its exponent field is always between 52 and 191, a normal float.
The kernel itself follows the six decisions in order:
float tl_expf(float x) { if (isnan(x)) return x + x; /* NaN in, quiet NaN out */ if (x > TL_EXP_HI) return INFINITY; /* also +inf */ if (x < TL_EXP_LO) return 0.0f; /* also -inf */
float kf = rintf(x * TL_LOG2E); /* nearest integer, ties to even */ int k = (int)kf; /* safe: |kf| <= 150 after the cutoffs */ float r = x - kf * TL_LN2_HI; /* exact: kf * LN2_HI has <= 17 bits, Sterbenz */ r = r - kf * TL_LN2_LO; /* the small correction, one small rounding */
float p = 1.0f / 5040.0f; /* 1/7!: Horner from the innermost coefficient */ p = p * r + 1.0f / 720.0f; p = p * r + 1.0f / 120.0f; p = p * r + 1.0f / 24.0f; p = p * r + 1.0f / 6.0f; p = p * r + 0.5f; p = p * r + 1.0f; p = p * r + 1.0f; /* p ~ e^r on |r| <= 0.3466 */
int k1 = k / 2, k2 = k - k1; /* both in [-75, 64] */ return p * pow2i(k1) * pow2i(k2); /* first product exact, second rounds once */}
void tl_exp_f32(const float *x, float *y, int64_t n) { for (int64_t i = 0; i < n; i++) y[i] = tl_expf(x[i]); /* read then write: y == x is safe */}Trace the hand example for : kf = rintf(1.442695) = 1; exactly, then ; the Horner chain gives ; , , and the result is , the float32 nearest .
The edges are where the split scale earns its keep. At the overflow edge , : a single pow2i(128) would be exponent field 255 (infinity), but and are both fine, and is finite because there. At , : , , the first product is a normal float and the second rounds once into the subnormal range. The left-to-right evaluation of p * pow2i(k1) * pow2i(k2) is what makes the first product the exact one. The full solution is in expf.c.
Why this design
Section titled “Why this design”The kernel costs three comparisons, one rintf, one multiply for , two multiply-subtracts for , seven multiply-adds, two integer shifts, and two multiplies: about 25 operations, no table, no division. The array form is and simple enough for a compiler to vectorize.
The C library’s expf is correctly rounded or close, but its speed and last-bit results differ between platforms, and it cannot be traced step by step against the Python twin. This version is within 1.21 ulp everywhere and identical on any IEEE platform with FP_CONTRACT OFF.
A degree-5 minimax polynomial reaches the same accuracy with two fewer multiply-adds. Taylor is kept because its remainder bound is derivable by hand and it matches the Taylor chapter’s coefficients exactly. Doing the reduction in double would also avoid the cancellation, but it doubles the width of a hot path and does not vectorize as well in float32 lanes; the Cody and Waite split costs one extra multiply-subtract. And the split scale beats a special subnormal path: two multiplies by normal powers of two handle both edges with one rounding, while branching on and building subnormal patterns by hand adds branches and bugs.
What can go wrong
Section titled “What can go wrong”The tests begin with the hand-worked inputs (, , give the bits above, and ) so everyone agrees on the algorithm. A differential test draws seeded and requires each to be within 2 ulp of exp in double, which is the accuracy the softmax’s tolerance budget from Error analysis, condition numbers, and tolerance budgets relies on. A sweep of every 512th float of (4 million inputs) covers the small logits that appear after max subtraction. The reduction boundaries get their own test: 64 floats on each side of for every , which is where is largest and the polynomial is at its worst.
At the overflow edge, must be finite and within 2 ulp, while the next float, FLT_MAX, and give ; this is the case that needs the split scale. At the underflow edge, must be within 2 ulp; below the normal range the result must satisfy FLT_MIN and be within one subnormal step (or 0); and , since masked attention scores are . NaN must stay NaN, with no undefined behavior, so that a NaN logit stays visible. The array form must give the scalar’s bits, write exactly elements, and work in place, because the softmax row is updated in place.
The mistakes these tests catch:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| stopping the Taylor polynomial at | about 3 ulp near | the Horner chain starts at |
reducing with one product, x - k * 0.69314718f | tens of ulps for large | TL_LN2_HI and TL_LN2_LO, two subtractions |
by truncation, (int)(x / ln 2) | up to , where degree 7 is 20 ulp off | rintf, nearest with ties to even |
| built in one piece | (exponent field 255) and garbage below | pow2i(k1) * pow2i(k2) with both halves in |
the overflow test written x >= 88.7228317f | the largest finite result becomes | x > TL_EXP_HI |
no NaN check before (int) | undefined behavior: UBSan aborts | isnan is the first line |
| no underflow cutoff | is undefined; large negative builds a garbage exponent | x < TL_EXP_LO returns 0 before is formed |
| the array loop off by one | the last element unwritten, or one past the end overwritten | for (int64_t i = 0; i < n; i++) |
Where this leads
Section titled “Where this leads”exp_range_reduced in Taylor series, remainder bounds, and range reduction is this algorithm in float64, and the differential test compares the two. In AI Engineering, the three-pass and online softmax kernels of Softmax in C: three-pass and online two-pass exponentiate each logit minus the row maximum; FlashAttention forward in C rescales its running softmax with ; Paged attention for decode in C computes the softmax over the keys of each block table; and Elementwise kernels in C computes SiLU in tl_silu_mul_f32. All of them call tl_expf per element.
Production implementations push each piece further. SLEEF’s expf (src/libm/sleefsp.c, xexpf) and Cephes’s expf.c use a degree-5 minimax polynomial (Remez algorithm) with the same accuracy and two fewer multiplies. SLEEF and XNNPACK vector exp routines process 8 or 16 lanes per instruction and round the reduction with the “add ” trick instead of rintf (XNNPACK src/f32-vscaleexpminusmax/). CORE-MATH’s expf is correctly rounded for every input, with a proof. And FlashAttention-3 uses exp2 with the factor folded into the score scale, so the reduction is a plain integer split.
Further reading
Section titled “Further reading”- Muller, Elementary Functions: Algorithms and Implementation (3rd ed.), chapters 2 and 11.
- Cody and Waite, Software Manual for the Elementary Functions (1980).
- Trefethen, Approximation Theory and Approximation Practice, chapter 10.
- Shah et al., FlashAttention-3 (2024), section 3.
- The CORE-MATH project (Inria).
Key terms
Section titled “Key terms”- Range reduction: rewriting so that the polynomial only needs to be accurate on a small interval around 0.
- Cody and Waite split: representing as a short high part, whose products with are exact, plus a small low part.
- Sterbenz’s lemma: if two floats are within a factor of 2 of each other, their difference is exact.
- Horner’s rule: evaluating a polynomial as nested multiply-adds from the innermost coefficient out.
- Minimax polynomial: the polynomial of a given degree that minimizes the worst-case error on an interval.
- Floating-point contraction: the compiler fusing
a * b + cinto a single fused multiply-add with one rounding.
Summary
Section titled “Summary”- Range reduction turns an infinite domain into a tiny one exactly: with and , and costs nothing because it is an exponent field.
- The reduction must not round away : is subtracted in two parts (Cody and Waite), a 9-bit high part whose product with is exact and a low part for the rest.
- On a Taylor polynomial of degree 7 is accurate to about , a tenth of a float32 ulp, so the result is within 1.21 ulp everywhere; degree 6 is not enough.
- runs from to , past both ends of the float exponent range, so is applied in two halves; the edges overflow to and underflow to exactly where the contract says.
- The C kernel is the Taylor chapter’s algorithm in float32, within 2 ulp of
exp_range_reducedon the float32 range.
Review questions
Section titled “Review questions”-
Why is chosen with only 9 significant bits?
Answer
So that is exact in float32: needs 8 bits and has 9, so the product has at most 17 significant bits, well under 24. Then subtracts two floats within a factor of 2 of each other, which Sterbenz’s lemma makes exact. All the rounding is pushed into , which is about times smaller.
-
Why does the overflow test use
>and not>=?Answer
TL_EXP_HIis the largest float whose exponential is still belowFLT_MAX. With>=, that input would return although its true result is finite and representable; the contract requires a finite value within 2 ulp there. -
Why is applied as two factors?
Answer
ranges from to , but a normal float’s exponent only covers to . A single
pow2i(128)would set the exponent field to 255 (infinity) andpow2i(-150)would underflow the field. Splitting into and , both in , keeps each factor a normal power of two; the first product is exact and the second rounds once, even when the result is subnormal. -
Why must the NaN and range checks come before
(int)kf?Answer
Converting NaN or an out-of-range float to
intis undefined behavior in C, and under UBSan it aborts. After the three checks, , so and the conversion is defined. The checks also give the exact contract values (, ) instead of whatever the arithmetic would produce. -
What does
#pragma STDC FP_CONTRACT OFFbuy, if a fused multiply-add is more accurate?Answer
Reproducibility. With contraction allowed, each compiler and target decides independently whether
p * r + cbecomes one FMA, so results differ in the last bit between machines and builds. Turning it off fixes the rounding sequence; the 1.21 ulp worst case is already inside the contract, so the extra accuracy is not needed.