Skip to content

8.1 Taylor series, remainder bounds, and range reduction

A CPU can add and multiply; it cannot compute exe^x. 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 exe^x 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.

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-nn Taylor polynomial of a function at a point and compute the coefficients of exe^x at 0 without forming factorials.
  • State the Lagrange remainder and use it to bound the error of er≈pn(r)e^r \approx p_n(r) at any point and degree.
  • Explain range reduction ex=2kere^x = 2^k e^r, why kk is rounded to nearest, and why kln⁡2k \ln 2 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_reduced and erf_series so they handle infinities, NaN, overflow, and underflow without warnings.

The notation used throughout the section is collected in one place first, since several symbols do double duty as code variables.

SymbolMeaningType / shape
f(i)(a)f^{(i)}(a)the ii-th derivative of ff at aa (f(0)=ff^{(0)} = f)float
i!i!1⋅2⋯i1 \cdot 2 \cdots i, with 0!=10! = 1integer
pn(x)p_n(x)the degree-nn Taylor polynomial of ff at aafloat
Rn(x)R_n(x)the remainder f(x)−pn(x)f(x) - p_n(x)float
xxthe input of exp_range_reducedfloat64 array
kkround⁡(x/ln⁡2)\operatorname{round}(x / \ln 2), an integerint
rrthe reduced argument x−kln⁡2x - k\ln 2, ∣r∣≤ln⁡22\lvert r \rvert \le \frac{\ln 2}{2}float64 array
tnt_nthe nn-th term of the erf seriesfloat64 array
NNthe number of erf terms summed (terms)int

Near a point aa, which polynomial of degree nn is the best stand-in for ff? The natural answer is the one whose value and first nn derivatives at aa equal ff‘s. Write p(x)=∑i=0nci(x−a)ip(x) = \sum_{i=0}^{n} c_i (x - a)^i. Differentiating ii times and setting x=ax = a kills every term but one, leaving p(i)(a)=i! cip^{(i)}(a) = i!\, c_i. Matching p(i)(a)=f(i)(a)p^{(i)}(a) = f^{(i)}(a) then fixes every coefficient:

pn(x)=∑i=0nf(i)(a)i!(x−a)i.p_n(x) = \sum_{i=0}^{n} \frac{f^{(i)}(a)}{i!} (x - a)^i .

For f=exf = e^x at a=0a = 0 every derivative is e0=1e^0 = 1, so pn(x)=1+x+x22+x36+⋯+xnn!p_n(x) = 1 + x + \frac{x^2}{2} + \frac{x^3}{6} + \cdots + \frac{x^n}{n!}, with coefficients 1/i!1/i!. The function exp_taylor_coeffs(n) returns them in ascending order of power, [1/0!,…,1/n!][1/0!, \ldots, 1/n!], which is the order horner takes (numpy’s polyval wants the reverse). Computing ci=ci−1/ic_i = c_{i-1}/i avoids forming i!i!, which overflows float64 at i=171i = 171.

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 ff has n+1n + 1 continuous derivatives, then for some ξ\xi between aa and xx,

Rn(x)=f(x)−pn(x)=f(n+1)(ξ)(n+1)!(x−a)n+1.R_n(x) = f(x) - p_n(x) = \frac{f^{(n+1)}(\xi)}{(n+1)!}(x - a)^{n+1} .

You do not know ξ\xi, but you can bound ∣f(n+1)∣|f^{(n+1)}| between aa and xx, 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 ere^r at 0, f(n+1)(ξ)=eξf^{(n+1)}(\xi) = e^\xi with ξ\xi between 0 and rr, so relative to ere^r:

∣er−pn(r)∣er=eξ−r ∣r∣n+1(n+1)!≤e∣r∣−r ∣r∣n+1(n+1)!.\frac{|e^r - p_n(r)|}{e^r} = \frac{e^{\xi - r}\,|r|^{n+1}}{(n+1)!} \le e^{|r| - r}\,\frac{|r|^{n+1}}{(n+1)!} .

The inequality on the right follows from two cases. If r>0r > 0 then ξ≤r\xi \le r and eξ−r≤1e^{\xi - r} \le 1; if r<0r < 0 then ξ≤0\xi \le 0 and eξ−r≤e−r=e∣r∣e^{\xi - r} \le e^{-r} = e^{|r|}. 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 nn but grows like ∣r∣n+1|r|^{n+1}: at r=0.35r = 0.35, degree 6 gives 1.2×10−71.2 \times 10^{-7}; at r=10r = 10, degree 6 gives 2000. A Taylor polynomial is only good near its center. The whole trick of computing exe^x, then, is to make sure the polynomial never sees a large argument.

Every real xx can be written x=kln⁡2+rx = k \ln 2 + r with kk an integer and ∣r∣≤ln⁡22≈0.3466|r| \le \frac{\ln 2}{2} \approx 0.3466: take k=round⁡(x/ln⁡2)k = \operatorname{round}(x / \ln 2). Then

ex=ekln⁡2⋅er=2k er,e^x = e^{k\ln 2} \cdot e^r = 2^k\, e^r ,

and multiplying by 2k2^k is exact in binary floating point, because it only changes the exponent field (np.ldexp(p, k)). So exe^x costs one reduction, one polynomial on ∣r∣≤0.3466|r| \le 0.3466, and one exponent adjustment, and the remainder bound of the previous section holds for every xx. With degree 6 the relative error is at most e2⋅0.3466 0.34667/7!=2.4×10−7e^{2 \cdot 0.3466}\,0.3466^7/7! = 2.4 \times 10^{-7}, 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 kk down (floor) instead of to nearest leaves r∈[0,ln⁡2)r \in [0, \ln 2), doubles the largest ∣r∣|r|, and multiplies the bound by 27=1282^7 = 128.

The reduction itself is a subtraction, and subtractions are where floating point bites. ln⁡2\ln 2 is irrational, so the float64 constant LN2 is off by up to ε/4\varepsilon/4 relative. Multiplied by k=1000k = 1000 that error lands in rr as 10−1310^{-13}, and ere^r 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 ln⁡2\ln 2 with the low 21 bits zero, so k⋅k \cdot LN2_HI is exact for ∣k∣<221|k| < 2^{21}, and LN2_LO =ln⁡2−= \ln 2 - LN2_HI is tiny. Then r=(x−k LN2_HI)−k LN2_LOr = (x - k\,\mathrm{LN2\_HI}) - k\,\mathrm{LN2\_LO} is accurate to the last bit.

exe^x overflows float64 above x≈709.78x \approx 709.78 and falls below the smallest subnormal under x≈−745.1x \approx -745.1. Clipping xx to [−750,710][-750, 710] first changes no result and keeps kk small; then +∞↦∞+\infty \mapsto \infty, −∞↦0-\infty \mapsto 0, and NaN is passed through separately.

The second function is erf, defined by erf⁡(x)=2π∫0xe−t2dt\operatorname{erf}(x) = \frac{2}{\sqrt\pi}\int_0^x e^{-t^2}dt. Integrating the Taylor series of e−t2e^{-t^2} term by term gives the textbook series

erf⁡(x)=2π∑n≥0(−1)nx2n+1n! (2n+1),\operatorname{erf}(x) = \frac{2}{\sqrt\pi} \sum_{n \ge 0} \frac{(-1)^n x^{2n+1}}{n!\,(2n+1)} ,

which converges for every xx but alternates in sign. That is a problem in floating point. At x=5x = 5 its largest term is about 6×1086 \times 10^{8}, 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 ex2erf⁡(x)e^{x^2}\operatorname{erf}(x) has only positive coefficients:

erf⁡(x)=2π e−x2∑n≥0tn,tn=2nx2n+11⋅3⋅5⋯(2n+1),tn+1tn=2x22n+3.\operatorname{erf}(x) = \frac{2}{\sqrt\pi}\, e^{-x^2} \sum_{n \ge 0} t_n, \qquad t_n = \frac{2^n x^{2n+1}}{1 \cdot 3 \cdot 5 \cdots (2n+1)}, \qquad \frac{t_{n+1}}{t_n} = \frac{2x^2}{2n+3} .

Every term has the sign of xx, 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 ρ=2x22N+3\rho = \frac{2x^2}{2N+3} is below 1, the ratios keep falling, so the omitted terms are at most a geometric series: ∑n≥Ntn≤tN1−ρ\sum_{n \ge N} t_n \le \frac{t_N}{1 - \rho}. (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 ∣x∣≥6|x| \ge 6, 1−erf⁡(x)<2.2×10−171 - \operatorname{erf}(x) < 2.2 \times 10^{-17}, below half the gap between 1 and the float before it, so erf rounds to exactly ±1\pm 1. The series would need hundreds of terms there, and near ∣x∣=27|x| = 27 its partial sums overflow while e−x2e^{-x^2} underflows to 0, giving $0 \cdot \infty = $ NaN. So erf_series returns sign⁡(x)\operatorname{sign}(x) for ∣x∣≥6|x| \ge 6. With 120 or more terms the result is within 3×10−153 \times 10^{-15} of erf everywhere.

Before writing code, run both algorithms on paper with low degree so that every intermediate number is visible.

Start with e1e^1 at degree 3. First reduce: k=round⁡(1/0.693147)=round⁡(1.4427)=1k = \operatorname{round}(1/0.693147) = \operatorname{round}(1.4427) = 1, so r=1−ln⁡2=0.3068528r = 1 - \ln 2 = 0.3068528. Then evaluate the polynomial:

p3(r)=1+r+r22+r36=1+0.3068528+0.0470793+0.0048155=1.3587476,p_3(r) = 1 + r + \frac{r^2}{2} + \frac{r^3}{6} = 1 + 0.3068528 + 0.0470793 + 0.0048155 = 1.3587476 ,

21⋅p3(r)=2.7174952vs.e=2.7182818.2^1 \cdot p_3(r) = 2.7174952 \quad \text{vs.} \quad e = 2.7182818 .

The relative error is 2.9×10−42.9 \times 10^{-4}, and the Lagrange bound (here r>0r > 0, so the factor is 1) is r4/4!=0.0088658/24=3.7×10−4r^4/4! = 0.0088658/24 = 3.7 \times 10^{-4}. The bound holds with little room to spare. Horner’s rule evaluates the same polynomial as 1+r(1+r(12+r⋅16))1 + r(1 + r(\frac12 + r \cdot \frac16)).

Now take erf⁡(0.5)\operatorname{erf}(0.5) with three terms. Here x2=0.25x^2 = 0.25, so the numerator of the ratio is 2x2=0.52x^2 = 0.5, divided by 2n+12n + 1: t0=0.5t_0 = 0.5, t1=0.5⋅0.5/3=0.0833333t_1 = 0.5 \cdot 0.5/3 = 0.0833333, t2=0.0833333⋅0.5/5=0.0083333t_2 = 0.0833333 \cdot 0.5/5 = 0.0083333, for a sum of 0.59166670.5916667. The prefactor is 2πe−0.25=1.1283792×0.7788008=0.8787826\frac{2}{\sqrt\pi} e^{-0.25} = 1.1283792 \times 0.7788008 = 0.8787826. The result is 0.8787826×0.5916667=0.51994640.8787826 \times 0.5916667 = 0.5199464, against erf⁡(0.5)=0.5204999\operatorname{erf}(0.5) = 0.5204999. The next term t3=0.000595t_3 = 0.000595 times the prefactor is 0.0005230.000523, and the tail bound t3/(1−0.5/9)t_3/(1 - 0.5/9) times the prefactor, 0.0005540.000554, covers the actual gap of 0.0005530.000553.

The module exposes one constant and three functions:

ERF_CUTOFF: float # 6.0
def 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 ±∞\pm\infty, NaN, overflow, and underflow without warnings. A negative n or deg, or terms < 1, raises ValueError.

The design follows directly from the principles above, one decision at a time.

  1. Coefficients by recurrence, ascending. ci=1/i!c_i = 1/i!, and ci=ci−1/ic_i = c_{i-1}/i builds them with one division each and never forms i!i!, which overflows at 171. Ascending order is what horner takes.
  2. Reduce first, so the bound is small everywhere. The remainder grows like ∣r∣n+1|r|^{n+1}, so the polynomial must only ever see small arguments. Writing x=kln⁡2+rx = k\ln 2 + r with k=round⁡(x/ln⁡2)k = \operatorname{round}(x/\ln 2) bounds ∣r∣≤ln⁡22|r| \le \frac{\ln 2}{2} for every xx, and ex=2kere^x = 2^k e^r with an exact rescaling.
  3. Round to nearest, not down. Nearest rounding centres rr on 0; flooring puts it in [0,ln⁡2)[0, \ln 2), doubles its largest size, and multiplies the degree-6 bound by 272^7.
  4. Subtract kln⁡2k\ln 2 in two exact pieces. With LN2_HI short enough that k⋅k \cdot LN2_HI has no rounding, x−k⋅LN2_HIx - k \cdot \text{LN2\_HI} is (nearly) exact, and the small correction k⋅k \cdot LN2_LO contributes only its own tiny rounding.
  5. Rescale by changing the exponent. np.ldexp(p, k) multiplies by 2k2^k without rounding; where the true result is beyond float64 it gives ∞\infty or 0, which is the correct answer.
  6. Keep the edges out of the arithmetic. Clip xx to [−750,710][-750, 710] so kk stays small and ±∞\pm\infty map to the right limits; take NaN out before clipping (where it would turn into a number) and put it back at the end.
  7. erf from the all-positive series. t0=xt_0 = x, tn+1=tn⋅2x22n+3t_{n+1} = t_n \cdot \frac{2x^2}{2n+3}, summed, times 2πe−x2\frac{2}{\sqrt\pi}e^{-x^2}. Every term has the sign of xx, so the sum has no cancellation.
  8. Cut off where erf is ±1\pm 1 in float64. For ∣x∣≥6|x| \ge 6 return sign⁡(x)\operatorname{sign}(x), and feed 0 into the series for those elements so the loop never overflows.

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-01
LN2_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 c

LN2 is only used to choose kk. An error in it can at worst pick a kk one off at a rounding tie, which still leaves ∣r∣|r| within the bound. The subtraction uses the split constants.

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 x=1x = 1, xc / LN2 is 1.44271.4427, so k=1k = 1; r=1−ln⁡2=0.3068528r = 1 - \ln 2 = 0.3068528; with deg=3, horner returns 1.35874761.3587476; ldexp doubles it to 2.71749522.7174952. For x=+∞x = +\infty the clip gives 710, k=1024k = 1024, and ldexp overflows to ∞\infty (quietly, inside errstate); for x=−∞x = -\infty the clip gives −750-750 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.

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 2x22n+1\frac{2x^2}{2n + 1}; that is the same recurrence as tn+1tn=2x22n+3\frac{t_{n+1}}{t_n} = \frac{2x^2}{2n+3} with the index shifted by one. terms counts t0,…,tterms−1t_0, \ldots, t_{\text{terms}-1}. For the hand example (terms=3, x=0.5x = 0.5): t1=0.5⋅0.5/3t_1 = 0.5 \cdot 0.5/3, t2=t1⋅0.5/5t_2 = t_1 \cdot 0.5/5, total 0.59166670.5916667, times 0.87878260.8787826 gives 0.51994640.5199464.

The full solution is taylor.py.

exp_range_reduced costs O(deg)O(\text{deg}) per element: one division, one rint, two multiply-subtracts, deg Horner steps, and one ldexp. erf_series costs O(terms)O(\text{terms}) 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 exe^x on [−87,88][-87, 88] would need hundreds of terms and would still lose digits to huge alternating terms for negative xx. Reduction makes degree 6 enough for float32 everywhere.

The two-part constant beats extended precision. A double-double ln⁡2\ln 2 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 ∣k∣<221|k| < 2^{21}, far beyond the ∣k∣≤1083|k| \le 1083 the clip allows.

The all-positive series beats the alternating one. Both converge, but in floating point only the positive one is accurate for ∣x∣|x| 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 (2x2=722x^2 = 72 at x=6x = 6, so the terms keep growing until n≈35n \approx 35), which is why the contract uses 120 or more.

A correct implementation must survive a specific set of checks. Each one exists because something downstream depends on it:

CaseKind of checkChecksWhy it matters downstream
the hand-worked e1e^1unit2.71749522.7174952, error 2.9×10−42.9 \times 10^{-4} inside the boundeveryone agrees on reduction and polynomial
inverse-factorial coefficientsunit[1,1,12,16,124][1, 1, \frac12, \frac16, \frac1{24}], length n+1n + 1, 1/30!1/30!the coefficient order horner and the C port use
the Lagrange boundpropertythe remainder bound at 4001 points, degrees 1 to 12the remainder bound is the design’s central property
degree 6 is float32-accurategoldenrelative error at most 2.4×10−72.4 \times 10^{-7} on [−87,88][-87, 88]tl_expf’s accuracy budget
full precision across the rangegoldendegree 20 within 10−1510^{-15} near ±700\pm 700the two-part reduction
special values and extremesboundary±∞\pm\infty, NaN, overflow, underflow, subnormal, no warningsmasked logits are −∞-\infty
shapes and scalarsunitscalars, matrices, integer input, deg < 0 raisescallers pass every shape
the hand-worked erf⁡(0.5)\operatorname{erf}(0.5)unit0.5199464the series and its ratio
erf against math.erfgolden160 terms within 3×10−153 \times 10^{-15} of math.erf on [−7,7][-7, 7]gelu_erf must match PyTorch
no cancellation at x=5x = 5boundaryx=3,4,5,−5.5x = 3, 4, 5, -5.5 to 3×10−153 \times 10^{-15}the alternating series fails here
erf cutoff and special valuesboundary±1\pm 1 at and beyond 6, ±∞\pm\infty, NaN, 0GELU feeds x/2x/\sqrt2 up to 28
the erf tail boundpropertythe geometric tail bound at many NN and xxthe 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 polyval is descending, horner ascending) evaluate the reversed polynomial; at degree 3 you get e1≈0.89e^1 \approx 0.89. exp_taylor_coeffs returns ascending coefficients and passes them to horner.

Rounding kk down instead of to nearest lets rr reach 0.69 and pushes the degree-6 error to 8×10−68 \times 10^{-6}; np.rint prevents it. Using one rounded ln⁡2\ln 2 in the reduction gives a relative error of 8×10−148 \times 10^{-14} near x=700x = 700; the two-part (xc - k * LN2_HI) - k * LN2_LO fixes it. Adding the low part of ln⁡2\ln 2 instead of subtracting it gives a relative error of 4×10−104 \times 10^{-10} per unit of kk; both parts must be subtracted. Coefficients 1/(i+1)!1/(i+1)! 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 enan=1e^{\mathrm{nan}} = 1; the NaN mask is restored at the end.

On the erf side, the alternating series gives only 7 correct digits at x=5x = 5, which is why the code uses the all-positive series times e−x2e^{-x^2}. Having no cutoff for large ∣x∣|x| gives NaN at x=28x = 28 and wrong values beyond 6; ERF_CUTOFF = 6.0 zeroes those inputs in the loop and replaces them by sign⁡(x)\operatorname{sign}(x). 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).

These functions are used immediately and then again much later. Back in Activation Functions and Their Derivatives, gelu_erf and dgelu_erf compute Φ(x)\Phi(x) 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 exe^x 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.

  • 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 sin⁡\sin and cos⁡\cos exactly for arguments like 1030010^{300}, where π\pi needs a thousand bits.
  • Abramowitz and Stegun 7.1.6: the erf series used here.
  • glibc exp and expf (sysdeps/ieee754/dbl-64/e_exp.c, sysdeps/ieee754/flt-32/e_expf.c): a 128-entry table of ej/128e^{j/128} makes rr 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 CUDA erff: branch-free vectorized approximations for whole SIMD lanes.
  • Taylor polynomial: the degree-nn polynomial whose value and first nn derivatives at a point match those of ff.
  • Lagrange remainder: the exact error f(n+1)(ξ)(x−a)n+1/(n+1)!f^{(n+1)}(\xi)(x-a)^{n+1}/(n+1)! of a Taylor polynomial, for some unknown ξ\xi between aa and xx.
  • Range reduction: rewriting ex=2kere^x = 2^k e^r so the polynomial only ever sees a small argument ∣r∣≤ln⁡22|r| \le \frac{\ln 2}{2}.
  • Cody-Waite reduction: subtracting kln⁡2k \ln 2 as two pieces, a short exact high part and a tiny low part, so rr 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.
  • The Taylor polynomial of degree nn matches ff and its first nn derivatives at a point; for exe^x at 0 its coefficients are 1/i!1/i!, built by ci=ci−1/ic_i = c_{i-1}/i.
  • The Lagrange remainder bounds the error exactly: ∣er−pn(r)∣≤emax⁡(r,0)∣r∣n+1/(n+1)!|e^r - p_n(r)| \le e^{\max(r, 0)} |r|^{n+1}/(n+1)!, tiny when ∣r∣|r| is small and useless when it is not.
  • Range reduction makes ∣r∣|r| small for every input: ex=2kere^x = 2^k e^r with k=round⁡(x/ln⁡2)k = \operatorname{round}(x/\ln 2) and ∣r∣≤ln⁡22|r| \le \frac{\ln 2}{2}; degree 6 is then float32-accurate.
  • Subtracting kln⁡2k \ln 2 in two parts (Cody and Waite) keeps rr exact to the last bit even for k=1000k = 1000.
  • A series can be correct and still useless in floating point: the alternating series for erf cancels catastrophically at x=5x = 5; the series with all terms of one sign does not.
  1. Why does exp_range_reduced round kk to nearest instead of taking the floor?

    Answer

    Rounding to nearest puts r=x−kln⁡2r = x - k\ln 2 in [−ln⁡22,ln⁡22][-\frac{\ln 2}{2}, \frac{\ln 2}{2}]; the floor puts it in [0,ln⁡2)[0, \ln 2), twice as far from the expansion point at worst. The degree-6 remainder scales like ∣r∣7|r|^7, so doubling ∣r∣|r| multiplies the bound by 27=1282^7 = 128; the measured degree-6 error rises to about 8×10−68 \times 10^{-6}, far outside float32 accuracy.

  2. What goes wrong with r = xc - k * LN2 near x=700x = 700, and why does the two-part form fix it?

    Answer

    LN2 differs from ln⁡2\ln 2 by about 2.3×10−172.3 \times 10^{-17}. Multiplied by k≈1000k \approx 1000 that is an absolute error of a few times 10−1410^{-14} in rr, and ere^r inherits it as a relative error, hundreds of times the float64 rounding level. LN2_HI has 21 trailing zero bits, so k⋅LN2_HIk \cdot \text{LN2\_HI} is exact for ∣k∣<221|k| < 2^{21} and so is x−k⋅LN2_HIx - k \cdot \text{LN2\_HI} in the cases that matter; the remaining k⋅LN2_LOk \cdot \text{LN2\_LO} is about 10−710^{-7}, and its rounding error is about 10−2310^{-23}, negligible.

  3. 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 to int32 gives an arbitrary integer and an “invalid value” warning. Computing on a harmless 0 and overwriting those positions with np.where(nan, np.nan, out) guarantees the right output and no warnings. Letting NaN become a number is the pitfall where enane^{\mathrm{nan}} comes out as 1.

  4. Why does erf_series zero out ∣x∣≥6|x| \ge 6 before the loop rather than just replacing the result afterwards?

    Answer

    np.where cannot prevent the loop from computing on those elements. For x=28x = 28 the partial sums grow past 1030810^{308} and overflow while e−x2e^{-x^2} underflows to 0, giving $0 \cdot \infty = $ NaN, with warnings, before the final where discards it. Feeding 0 into the series for those elements keeps every intermediate finite; the answer sign⁡(x)\operatorname{sign}(x) is then substituted.

  5. The hand-worked e1e^1 example shows a relative error of 2.9×10−42.9 \times 10^{-4} against a bound of 3.7×10−43.7 \times 10^{-4}. Why is the bound always above the error, and why is it so tight here?

    Answer

    The Lagrange remainder is exact for some ξ\xi between 0 and rr: the error is eξr44!\frac{e^\xi r^4}{4!}, and bounding eξ−r≤1e^{\xi - r} \le 1 (since r>0r > 0) can only make it larger. It is tight because the next Taylor term r4/4!r^4/4! dominates the remainder when rr is small: the omitted terms after it are a factor of about r/5≈0.06r/5 \approx 0.06 smaller each.