8.1 Taylor series, remainder bounds, and range reduction
A CPU can add and multiply; it cannot compute . Up to this point numpy has done that work for you, but the optional C kernels later in AI Engineering must do it themselves: softmax in C exponentiates every logit, and the SiLU kernel exponentiates every activation. The way every math library computes is a polynomial on a small interval plus an exact rescaling. The polynomial comes from the Taylor series, and the Taylor series comes with an error bound that tells you which degree is enough.
Concepts from other sections (11)
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.
- Taylor series: the power series built from the derivatives of at ; truncating it gives the polynomials that libraries use to compute , , and . Read more: Chapter 8: Calculus 2
- GELU: , the input weighted by the standard normal CDF; its tanh approximation is a different function. 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
- Geometric series: , with partial sum and limit for . Read more: 8.2 Series convergence, the EMA as a geometric series, and bias correction
- Horner’s rule: evaluating from the inside out, with multiplications and additions. Read more: 6.4 Polynomials, Horner’s rule, and stable quadratic roots
- Stable quadratic formula: with roots and , which never subtracts nearly equal numbers. Read more: 6.4 Polynomials, Horner’s rule, and stable quadratic roots
- Minimax polynomial: the polynomial of a given degree that minimizes the worst-case error on an interval. Read more: 15.6 Polynomial approximation and range reduction: expf in C
- 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
- Forward mode: automatic differentiation that carries tangents alongside values, costing one pass per input direction. Read more: 14.1 Dual numbers and forward-mode autodiff
- stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement in AI Engineering - rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
The same tools give you erf, which the exact GELU in Activation Functions and Their Derivatives needs. This section builds both in Python, where you can watch the error bound hold point by point, so that the C port in Polynomial approximation and range reduction: expf in C has a trusted reference to check against.
You will lean on two earlier sections. Polynomials, Horner, and stable quadratic roots supplies the horner evaluator that runs every polynomial here, and Derivatives and finite differences used the first few terms of Taylor’s formula informally; this section proves the full version. The finished code is in course/solutions/python/tinyllm/num/taylor.py, and its interface is fixed by the contract course/contracts/py/tinyllm/num/taylor.pyi.
Learning objectives
- Derive the degree- Taylor polynomial of a function at a point and compute the coefficients of at 0 without forming factorials.
- State the Lagrange remainder and use it to bound the error of at any point and degree.
- Explain range reduction , why is rounded to nearest, and why is subtracted in two parts.
- Recognize catastrophic cancellation in an alternating series and replace it with an all-positive series for erf, with a geometric tail bound.
- Implement
exp_range_reducedanderf_seriesso they handle infinities, NaN, overflow, and underflow without warnings.
Polynomials that match derivatives
Section titled “Polynomials that match derivatives”The notation used throughout the section is collected in one place first, since several symbols do double duty as code variables.
| Symbol | Meaning | Type / shape |
|---|---|---|
| the -th derivative of at () | float | |
| , with | integer | |
| the degree- Taylor polynomial of at | float | |
| the remainder | float | |
the input of exp_range_reduced | float64 array | |
| , an integer | int | |
| the reduced argument , | float64 array | |
| the -th term of the erf series | float64 array | |
the number of erf terms summed (terms) | int |
Near a point , which polynomial of degree is the best stand-in for ? The natural answer is the one whose value and first derivatives at equal ‘s. Write . Differentiating times and setting kills every term but one, leaving . Matching then fixes every coefficient:
For at every derivative is , so , with coefficients . The function exp_taylor_coeffs(n) returns them in ascending order of power, , which is the order horner takes (numpy’s polyval wants the reverse). Computing avoids forming , which overflows float64 at .
The remainder tells you how wrong you are
Section titled “The remainder tells you how wrong you are”A polynomial that matches derivatives at one point is only useful if you know how far it drifts away from that point. Taylor’s theorem in Lagrange form answers exactly that: if has continuous derivatives, then for some between and ,
You do not know , but you can bound between and , and that bounds the error. (The finite-difference analysis in Derivatives and finite differences used the first terms of this formula; this is the proven version.) For at 0, with between 0 and , so relative to :
The inequality on the right follows from two cases. If then and ; if then and . The bound holds at every point and every degree, so it is a property any correct implementation can be checked against.
Read the bound carefully and you see both its power and its limit. It shrinks factorially in but grows like : at , degree 6 gives ; at , degree 6 gives 2000. A Taylor polynomial is only good near its center. The whole trick of computing , then, is to make sure the polynomial never sees a large argument.
Range reduction: keep the argument small
Section titled “Range reduction: keep the argument small”Every real can be written with an integer and : take . Then
and multiplying by is exact in binary floating point, because it only changes the exponent field (np.ldexp(p, k)). So costs one reduction, one polynomial on , and one exponent adjustment, and the remainder bound of the previous section holds for every . With degree 6 the relative error is at most , about two float32 units in the last place. That is the accuracy target of tl_expf in the C port.
The choice of rounding matters. Rounding down (floor) instead of to nearest leaves , doubles the largest , and multiplies the bound by .
Subtracting exactly
Section titled “Subtracting kln2k \ln 2kln2 exactly”The reduction itself is a subtraction, and subtractions are where floating point bites. is irrational, so the float64 constant LN2 is off by up to relative. Multiplied by that error lands in as , and inherits it: 400 times the float64 rounding level.
Cody and Waite’s fix is to split the constant. LN2_HI holds the first 32 bits of with the low 21 bits zero, so LN2_HI is exact for , and LN2_LO LN2_HI is tiny. Then is accurate to the last bit.
The edges of the range
Section titled “The edges of the range”overflows float64 above and falls below the smallest subnormal under . Clipping to first changes no result and keeps small; then , , and NaN is passed through separately.
A series for erf without cancellation
Section titled “A series for erf without cancellation”The second function is erf, defined by . Integrating the Taylor series of term by term gives the textbook series
which converges for every but alternates in sign. That is a problem in floating point. At its largest term is about , the sum is below 1, and float64 keeps 16 significant digits of each term, so the cancellation leaves about 7 correct digits of the answer.
The fix is a different series for the same function. The Taylor series of has only positive coefficients:
Every term has the sign of , so nothing cancels, and each term comes from the previous one by one multiplication.
This series also has a clean tail bound. Once the ratio is below 1, the ratios keep falling, so the omitted terms are at most a geometric series: . (Geometric series are the subject of the next section, Series convergence, the EMA as a geometric series, and bias correction.)
Finally, there is a cutoff. For , , below half the gap between 1 and the float before it, so erf rounds to exactly . The series would need hundreds of terms there, and near its partial sums overflow while underflows to 0, giving $0 \cdot \infty = $ NaN. So erf_series returns for . With 120 or more terms the result is within of erf everywhere.
Working it by hand
Section titled “Working it by hand”Before writing code, run both algorithms on paper with low degree so that every intermediate number is visible.
Start with at degree 3. First reduce: , so . Then evaluate the polynomial:
The relative error is , and the Lagrange bound (here , so the factor is 1) is . The bound holds with little room to spare. Horner’s rule evaluates the same polynomial as .
Now take with three terms. Here , so the numerator of the ratio is , divided by : , , , for a sum of . The prefactor is . The result is , against . The next term times the prefactor is , and the tail bound times the prefactor, , covers the actual gap of .
Designing the interface
Section titled “Designing the interface”The module exposes one constant and three functions:
ERF_CUTOFF: float # 6.0def exp_taylor_coeffs(n: int) -> NDArray: ... # [1/0!, ..., 1/n!]def exp_range_reduced(x: ArrayLike, deg: int = 6) -> NDArray: ...def erf_series(x: ArrayLike, terms: int) -> NDArray: ...All arithmetic is float64, and results have the shape of x. exp_range_reduced handles , NaN, overflow, and underflow without warnings. A negative n or deg, or terms < 1, raises ValueError.
Building it step by step
Section titled “Building it step by step”The design follows directly from the principles above, one decision at a time.
- Coefficients by recurrence, ascending. , and builds them with one division each and never forms , which overflows at 171. Ascending order is what
hornertakes. - Reduce first, so the bound is small everywhere. The remainder grows like , so the polynomial must only ever see small arguments. Writing with bounds for every , and with an exact rescaling.
- Round to nearest, not down. Nearest rounding centres on 0; flooring puts it in , doubles its largest size, and multiplies the degree-6 bound by .
- Subtract in two exact pieces. With
LN2_HIshort enough thatLN2_HIhas no rounding, is (nearly) exact, and the small correctionLN2_LOcontributes only its own tiny rounding. - Rescale by changing the exponent.
np.ldexp(p, k)multiplies by without rounding; where the true result is beyond float64 it gives or 0, which is the correct answer. - Keep the edges out of the arithmetic. Clip to so stays small and map to the right limits; take NaN out before clipping (where it would turn into a number) and put it back at the end.
- erf from the all-positive series. , , summed, times . Every term has the sign of , so the sum has no cancellation.
- Cut off where erf is in float64. For return , and feed 0 into the series for those elements so the loop never overflows.
The constants and the coefficients
Section titled “The constants and the coefficients”The listing opens with the constants and the coefficient builder:
ERF_CUTOFF = 6.0 # erfc(6) = 2.2e-17 < half an ulp of 1.0: erf(x) rounds to sign(x)LN2 = math.log(2.0)# Cody and Waite: ln 2 split so that k * LN2_HI is exact for |k| < 2**21# (LN2_HI has 21 trailing zero bits) and LN2_LO carries the rest.LN2_HI = 6.93147180369123816490e-01LN2_LO = 1.90821492927058770002e-10
def exp_taylor_coeffs(n: int) -> NDArray: if n < 0: raise ValueError(f"degree n must be >= 0, got {n}") c = np.empty(int(n) + 1, dtype=np.float64) c[0] = 1.0 for i in range(1, int(n) + 1): c[i] = c[i - 1] / i # 1/i! = (1/(i-1)!) / i, no factorial overflow return cLN2 is only used to choose . An error in it can at worst pick a one off at a rounding tie, which still leaves within the bound. The subtraction uses the split constants.
The exponential
Section titled “The exponential”With the coefficients in hand, exp_range_reduced is the reduction, the polynomial, and the rescaling, wrapped in the edge handling:
def exp_range_reduced(x: ArrayLike, deg: int = 6) -> NDArray: if deg < 0: raise ValueError(f"deg must be >= 0, got {deg}") x = np.asarray(x, dtype=np.float64) nan = np.isnan(x) # remembered, restored at the end # exp(-750) is below the smallest subnormal and exp(710) above the # largest double, so clipping changes no result and keeps k small. xc = np.clip(np.where(nan, 0.0, x), -750.0, 710.0) k = np.rint(xc / LN2) # round half to even: |r| <= ln(2) / 2 r = (xc - k * LN2_HI) - k * LN2_LO # two-part reduction (step 4) # Ascending coefficients, the order horner (M00.4) takes; numpy.polyval # wants them descending. p = horner(exp_taylor_coeffs(deg), r) # e^r on |r| <= 0.3466 with np.errstate(over="ignore", under="ignore"): out = np.ldexp(p, k.astype(np.int32)) # times 2^k, exact; inf or 0 at the edges return np.where(nan, np.nan, out)Trace the hand example through it. With , xc / LN2 is , so ; ; with deg=3, horner returns ; ldexp doubles it to . For the clip gives 710, , and ldexp overflows to (quietly, inside errstate); for the clip gives and ldexp underflows to 0. The parentheses in (xc - k * LN2_HI) - k * LN2_LO matter: the large, exact cancellation happens first, and the small correction is subtracted from the already small result.
The error function
Section titled “The error function”erf_series applies the same edge discipline to the all-positive series:
def erf_series(x: ArrayLike, terms: int) -> NDArray: if terms < 1: raise ValueError(f"terms must be >= 1, got {terms}") x = np.asarray(x, dtype=np.float64) big = np.abs(x) >= ERF_CUTOFF # includes +-inf xs = np.where(big | np.isnan(x), 0.0, x) # the loop only sees safe inputs x2 = xs * xs # t_0 = x, t_{n+1} = t_n * 2 x^2 / (2n + 3): every term has the sign of x. term = xs.copy() total = xs.copy() for n in range(1, int(terms)): term = term * (2.0 * x2) / (2 * n + 1) # t_n from t_{n-1}: one multiply, one divide total = total + term out = (2.0 / math.sqrt(math.pi)) * np.exp(-x2) * total out = np.where(big, np.sign(x), out) # erf is +-1 to float64 beyond the cutoff return np.where(np.isnan(x), np.nan, out)The loop index n here is the index of the term being produced, so its ratio is ; that is the same recurrence as with the index shifted by one. terms counts . For the hand example (terms=3, ): , , total , times gives .
The full solution is taylor.py.
Why this design
Section titled “Why this design”exp_range_reduced costs per element: one division, one rint, two multiply-subtracts, deg Horner steps, and one ldexp. erf_series costs per element; 160 terms is expensive, but this is a float64 reference, not the production erf (see Further reading).
Range reduction beats simply raising the degree. Without reduction, a Taylor polynomial for on would need hundreds of terms and would still lose digits to huge alternating terms for negative . Reduction makes degree 6 enough for float32 everywhere.
The two-part constant beats extended precision. A double-double or np.longdouble would also work, but it is slower and does not port to C; the Cody-Waite split costs one extra multiply-subtract and is exact for every , far beyond the the clip allows.
The all-positive series beats the alternating one. Both converge, but in floating point only the positive one is accurate for beyond about 3. Choosing the representation that does not cancel is the same lesson as the stable quadratic formula in Polynomials, Horner, and stable quadratic roots.
Some tradeoffs are accepted knowingly. Taylor coefficients are not optimal on an interval: a minimax polynomial reaches the same accuracy with a degree or two fewer. Taylor is kept because its remainder bound is provable by hand, which makes it the right reference for the C port. The erf series near the cutoff also needs many terms ( at , so the terms keep growing until ), which is why the contract uses 120 or more.
What can go wrong
Section titled “What can go wrong”A correct implementation must survive a specific set of checks. Each one exists because something downstream depends on it:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the hand-worked | unit | , error inside the bound | everyone agrees on reduction and polynomial |
| inverse-factorial coefficients | unit | , length , | the coefficient order horner and the C port use |
| the Lagrange bound | property | the remainder bound at 4001 points, degrees 1 to 12 | the remainder bound is the design’s central property |
| degree 6 is float32-accurate | golden | relative error at most on | tl_expf’s accuracy budget |
| full precision across the range | golden | degree 20 within near | the two-part reduction |
| special values and extremes | boundary | , NaN, overflow, underflow, subnormal, no warnings | masked logits are |
| shapes and scalars | unit | scalars, matrices, integer input, deg < 0 raises | callers pass every shape |
| the hand-worked | unit | 0.5199464 | the series and its ratio |
erf against math.erf | golden | 160 terms within of math.erf on | gelu_erf must match PyTorch |
| no cancellation at | boundary | to | the alternating series fails here |
| erf cutoff and special values | boundary | at and beyond 6, , NaN, 0 | GELU feeds up to 28 |
| the erf tail bound | property | the geometric tail bound at many and | the remainder for erf |
The mistakes that break these checks are worth knowing by their symptoms, because each produces a recognizable wrong number.
Warning: Coefficients in the wrong order for the evaluator (numpy’s
polyvalis descending,hornerascending) evaluate the reversed polynomial; at degree 3 you get .exp_taylor_coeffsreturns ascending coefficients and passes them tohorner.
Rounding down instead of to nearest lets reach 0.69 and pushes the degree-6 error to ; np.rint prevents it. Using one rounded in the reduction gives a relative error of near ; the two-part (xc - k * LN2_HI) - k * LN2_LO fixes it. Adding the low part of instead of subtracting it gives a relative error of per unit of ; both parts must be subtracted. Coefficients make every value wrong; the code sets c[0] = 1.0 and then c[i] = c[i - 1] / i. Letting NaN pass through the clip as 0 yields ; the NaN mask is restored at the end.
On the erf side, the alternating series gives only 7 correct digits at , which is why the code uses the all-positive series times . Having no cutoff for large gives NaN at and wrong values beyond 6; ERF_CUTOFF = 6.0 zeroes those inputs in the loop and replaces them by . An off-by-one in the erf ratio or term count shows up as a wrong third term in the hand example; the ratio must be 2.0 * x2 / (2 * n + 1) for term n, with the loop over range(1, terms).
Where this leads
Section titled “Where this leads”These functions are used immediately and then again much later. Back in Activation Functions and Their Derivatives, gelu_erf and dgelu_erf compute with erf_series(x / sqrt(2), 160). Dual numbers and forward-mode autodiff differentiates erf in forward mode with dual_erf, which uses the same series. Stable numerics: logsumexp, softmax, and compensated sums explains why overflows at 709.78 and how stable softmax avoids it. And Polynomial approximation and range reduction: expf in C builds tl_expf with the same reduction and a degree-6 polynomial in float32, checked against this Python.
Further reading
Section titled “Further reading”- OpenStax, Calculus Volume 2 (free), sections 6.3 and 6.4: Taylor and Maclaurin series and the remainder.
- Muller, Elementary Functions: Algorithms and Implementation, ch. 11: range reduction, Cody and Waite, and Payne and Hanek reduction, which reduces and exactly for arguments like , where needs a thousand bits.
- Abramowitz and Stegun 7.1.6: the erf series used here.
- glibc
expandexpf(sysdeps/ieee754/dbl-64/e_exp.c,sysdeps/ieee754/flt-32/e_expf.c): a 128-entry table of makes even smaller and the polynomial shorter, and the results are correctly rounded in most cases. - Minimax polynomials via the Remez algorithm (the Sollya tool): the polynomial with the smallest maximum error on the interval rather than the best at one point, one or two degrees fewer for the same accuracy. The C port discusses this further.
- SLEEF (
src/libm/sleefsimdsp.c) and CUDAerff: branch-free vectorized approximations for whole SIMD lanes.
Key terms
Section titled “Key terms”- Taylor polynomial: the degree- polynomial whose value and first derivatives at a point match those of .
- Lagrange remainder: the exact error of a Taylor polynomial, for some unknown between and .
- Range reduction: rewriting so the polynomial only ever sees a small argument .
- Cody-Waite reduction: subtracting as two pieces, a short exact high part and a tiny low part, so is accurate to the last bit.
- Catastrophic cancellation: loss of significant digits when large terms of opposite sign nearly cancel.
- Tail bound: an upper bound on the sum of the omitted terms of a series, here a geometric series.
Summary
Section titled “Summary”- The Taylor polynomial of degree matches and its first derivatives at a point; for at 0 its coefficients are , built by .
- The Lagrange remainder bounds the error exactly: , tiny when is small and useless when it is not.
- Range reduction makes small for every input: with and ; degree 6 is then float32-accurate.
- Subtracting in two parts (Cody and Waite) keeps exact to the last bit even for .
- A series can be correct and still useless in floating point: the alternating series for erf cancels catastrophically at ; the series with all terms of one sign does not.
Review questions
Section titled “Review questions”-
Why does
exp_range_reducedround to nearest instead of taking the floor?Answer
Rounding to nearest puts in ; the floor puts it in , twice as far from the expansion point at worst. The degree-6 remainder scales like , so doubling multiplies the bound by ; the measured degree-6 error rises to about , far outside float32 accuracy.
-
What goes wrong with
r = xc - k * LN2near , and why does the two-part form fix it?Answer
LN2differs from by about . Multiplied by that is an absolute error of a few times in , and inherits it as a relative error, hundreds of times the float64 rounding level.LN2_HIhas 21 trailing zero bits, so is exact for and so is in the cases that matter; the remaining is about , and its rounding error is about , negligible. -
Why does the function replace NaN with 0 before clipping and restore it at the end, instead of letting NaN flow through?
Answer
NaN must come out as NaN, but the steps in between are not NaN-safe:
np.rint(nan)cast toint32gives an arbitrary integer and an “invalid value” warning. Computing on a harmless 0 and overwriting those positions withnp.where(nan, np.nan, out)guarantees the right output and no warnings. Letting NaN become a number is the pitfall where comes out as 1. -
Why does
erf_serieszero out before the loop rather than just replacing the result afterwards?Answer
np.wherecannot prevent the loop from computing on those elements. For the partial sums grow past and overflow while underflows to 0, giving $0 \cdot \infty = $ NaN, with warnings, before the finalwherediscards it. Feeding 0 into the series for those elements keeps every intermediate finite; the answer is then substituted. -
The hand-worked example shows a relative error of against a bound of . Why is the bound always above the error, and why is it so tight here?
Answer
The Lagrange remainder is exact for some between 0 and : the error is , and bounding (since ) can only make it larger. It is tight because the next Taylor term dominates the remainder when is small: the omitted terms after it are a factor of about smaller each.