6.4 Polynomials, Horner's rule, and stable quadratic roots
Every activation function and every softmax in the models calls , and so far numpy has computed it for you. Once the C kernels arrive in AI Engineering, softmax and SiLU need their own tl_expf, and Polynomial approximation and expf builds it the way every math library does: reduce to a small range, then evaluate a polynomial that approximates there. Taylor series first derives those polynomials and evaluates them in Python. Both evaluate with Horner’s rule, the first subject of this section, and both depend on how the order of evaluation changes the rounding error.
Concepts from other sections (6)
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.
- activation function: a nonlinear function applied elementwise between linear layers. Read more: 7.3 Activation Functions and Their Derivatives
- rounding error: the error from floating-point rounding, about in a difference quotient. Read more: 7.1 Derivatives and Finite Differences
- Unit roundoff: , the largest relative error of a single round-to-nearest. Read more: 15.1 IEEE 754 anatomy, ulps, and round to nearest even
- One-to-one: different inputs always give different outputs; exactly the functions with an inverse. Read more: 6.5 Problem set: functions, logarithms, trigonometry, series, polynomials, and inequalities
- 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
- Range reduction: rewriting so the polynomial only ever sees a small argument . Read more: 8.1 Taylor series, remainder bounds, and range reduction
The second half of the section is the smallest example of a theme that runs through this book: a formula that is correct on paper and wrong in floating point. The quadratic formula you learned in school loses the small root of entirely, and a two-line rewrite fixes it. You will need only exponents and powers from Exponents, logarithms, and units of information, and numpy arrays and broadcasting from Python and numpy in Programming and Algorithms.
The finished code is course/solutions/python/tinyllm/num/poly.py, which provides horner and quadratic_roots; its interface is fixed by the contract course/contracts/py/tinyllm/num/poly.pyi.
Learning objectives
- Evaluate a polynomial stored in ascending coefficient order with Horner’s rule, and state its cost and its error bound.
- Explain when Horner’s rule is exact, and why its relative error is large near a root no matter the evaluation order.
- Derive the quadratic formula and Vieta’s formulas, and show why the textbook formula cancels catastrophically when .
- Implement the stable quadratic formula, including and power-of-two scaling against overflow.
Polynomials and their roots
Section titled “Polynomials and their roots”The symbols used throughout are collected here first:
| Symbol | Meaning | Type / shape |
|---|---|---|
| the degree: the highest power with a nonzero coefficient | int | |
| coefficients, ascending: multiplies | Sequence[float] | |
| the polynomial | NDArray | |
| a root: a number with | float | |
| the coefficients of the quadratic , | float | |
| the discriminant, | float | |
| the two roots, | float | |
| the stable intermediate | float | |
| float64 unit roundoff, | ||
| , the bound on rounded operations | float |
A polynomial of degree is with . It is determined by its coefficient list, which this book writes in ascending order of power: is , and coeffs[k] multiplies . numpy’s np.polyval takes the opposite, descending order, while numpy.polynomial.polynomial.polyval takes ascending; mixing the two is the first mistake to guard against.
A root is an with . The factor theorem says exactly when divides , that is, for a polynomial of degree . Dividing out one root at a time shows that a degree- polynomial has at most roots. For example, is 0 at , and dividing by leaves .
Horner’s rule
Section titled “Horner’s rule”Evaluating term by term computes every power separately. Factoring out repeatedly gives the nested form
which is evaluated from the inside out:
acc = 0for k = n, n-1, ..., 0: # highest power first acc = acc * x + c[k]That is multiplications and additions (the first step multiplies 0), the fewest possible for a general polynomial, and one fused multiply-add per coefficient in C. Horner’s intermediate values are also the coefficients of the quotient when you evaluate at , with the remainder last; this is “synthetic division”. Starting from acc = 0 makes the empty coefficient list the zero polynomial, and it works the same for a scalar or a whole array of points.
How accurate is Horner’s rule?
Section titled “How accurate is Horner’s rule?”Each step rounds twice, once for the multiplication and once for the addition, each with relative error at most . Following those errors through the steps (Higham, chapter 5) bounds the computed value :
Notice that the right side is the size of the largest terms, not of the result. When terms of opposite sign nearly cancel, as they do near a root, the relative error of can be large. That comes from the polynomial being ill-conditioned there, and no evaluation order fixes it. At the other extreme, when all the inputs are integers and every partial result acc stays below , no step rounds at all and Horner’s rule is exact.
The quadratic formula
Section titled “The quadratic formula”Now the second problem. For with , divide by and complete the square:
gives two real roots, a double root , and none (two complex roots, which quadratic_roots rejects). Expanding and matching coefficients gives Vieta’s formulas, true for any quadratic:
Cancellation and the stable formula
Section titled “Cancellation and the stable formula”When , is very close to . One of the two signs in then subtracts two nearly equal numbers. Each has a rounding error of about , the difference is tiny, and the error is a large fraction of it: catastrophic cancellation. The other sign adds two numbers of the same sign and is accurate. So compute only the safe one,
where the second root comes from Vieta: and give . Neither step subtracts.
Two details make the formula robust. First, must be when . numpy.sign(0) is 0, which makes for ; with , only when and , the double root 0. Second, overflows to infinity once . Dividing , , by the same power of two first is exact in binary floating point and does not change the roots, and it keeps every intermediate in range. The roots are returned sorted, .
Working it by hand
Section titled “Working it by hand”Start with Horner’s rule on , coefficients , at . The loop runs from the highest power down:
| step | acc * x + c[k] | acc | |
|---|---|---|---|
| 1 | 2 | 3 | |
| 2 | 1 | 8 | |
| 3 | 0 | 17 |
Check: , with two multiplications and two additions. At the values are .
Next, a friendly quadratic, . , and so , giving . The roots are and , sorted . Vieta checks out: and .
Now the cancellation case, . Exactly, and the roots are , about and . Follow it in float64. First, ; near , consecutive float64 values are apart, so it rounds to . The textbook small root is then , while the true value is : 25% wrong, with every digit lost to the subtraction. The stable formula instead computes to 16 digits, so and , correct to the last digit.
Designing the interface
Section titled “Designing the interface”Two functions suffice:
def horner(coeffs: Sequence[float], x: ArrayLike) -> NDArray: ... # ascending coeffs, float64, x's shapedef quadratic_roots(a: float, b: float, c: float) -> tuple[float, float]: ... # x1 <= x2, no cancellationquadratic_roots raises ValueError when (a linear equation), when (complex roots), and when a coefficient is NaN or infinite.
Building it step by step
Section titled “Building it step by step”Eight observations fix the implementation.
- Store coefficients ascending, evaluate descending.
coeffs[k]multiplies , but Horner’s nesting starts from the innermost bracket, which holds the highest coefficient . So the loop walks the list in reverse. - Start from zero, not from . With
acc = 0, the first step computes , so no special case is needed for the first coefficient, and an empty list returns the zero polynomial. Makingaccan array of zeros shaped like lets one loop evaluate at every point at once. - Reject what has no two real roots. Non-finite coefficients, (linear), and (complex) all raise, so a caller never receives a NaN pair it has to recognise.
- Scale before squaring. overflows for . Multiplying by the same nonzero number does not move the roots, and multiplying by a power of two is exact in binary floating point. Scaling by , where is just above the largest coefficient magnitude, puts the largest coefficient in , so and cannot overflow.
- Compute only the sign of that adds. With chosen to match , the sum adds two numbers of the same sign, so carries full relative precision. must take : then , which is nonzero whenever .
- Get the other root from Vieta, not from the dangerous sign. is one root; since , the other is . A division does not cancel.
- Handle the one remaining zero. only if and , which forces : the equation is , with the double root 0. Return it rather than dividing .
- Sort. Which of and is smaller depends on the signs of , , , so the result is sorted explicitly.
Horner’s rule in code
Section titled “Horner’s rule in code”def horner(coeffs: Sequence[float], x: ArrayLike) -> NDArray: c = [float(v) for v in coeffs] # accepts any sequence, computes in float64 xs = np.asarray(x, dtype=np.float64) # float32 or int input is promoted; shape kept acc = np.zeros_like(xs) # the empty sum: the zero polynomial # Innermost bracket first: start at the highest power and work down. for ck in reversed(c): acc = acc * xs + ck # one multiply and one add per coefficient return accreversed(c) is the whole difference between ascending and descending storage. On the hand example, reversed([1, 2, 3]) yields 3, 2, 1, and acc goes . Because acc and xs are arrays, the same four lines evaluate a scalar, a vector of points, or a 2-D grid; np.zeros_like of a 0-d array is a 0-d array, so a scalar x gives a 0-d result.
The stable quadratic in code
Section titled “The stable quadratic in code”def quadratic_roots(a: float, b: float, c: float) -> tuple[float, float]: a, b, c = float(a), float(b), float(c) if not all(math.isfinite(v) for v in (a, b, c)): raise ValueError(f"coefficients must be finite, got {a}, {b}, {c}") if a == 0.0: raise ValueError("a == 0: the equation is linear, not quadratic") # Scale by a power of two (exact) so that b * b cannot overflow when |b| # is near 1e200; the roots of s a x^2 + s b x + s c are the same. e = math.frexp(max(abs(a), abs(b), abs(c)))[1] # max = m * 2^e with 0.5 <= m < 1 a, b, c = math.ldexp(a, -e), math.ldexp(b, -e), math.ldexp(c, -e) disc = b * b - 4.0 * a * c if disc < 0.0: raise ValueError(f"discriminant {disc} < 0: the roots are complex") # q = -(b + sign(b) sqrt(disc)) / 2 adds two numbers of the same sign, so # nothing cancels. sign(0) is taken as +1: numpy's sign(0) = 0 would # make q = 0 for x^2 - 4. sign = 1.0 if b >= 0.0 else -1.0 q = -0.5 * (b + sign * math.sqrt(disc)) if q == 0.0: # b == 0 and disc == 0, so c == 0: the double root 0 return (0.0, 0.0) # One root is q / a; Vieta (x1 x2 = c / a) gives the other as c / q. r1, r2 = q / a, c / q return (r1, r2) if r1 <= r2 else (r2, r1)math.frexp(v) returns with and , and math.ldexp(v, -e) multiplies by by adjusting the exponent field only, so the scaling introduces no rounding. The roots come out at the original scale without unscaling, because and are ratios of scaled quantities. For , becomes about and ; underflows to 0, which is harmless because it is negligible next to ; , , and .
Trace the cancellation case, . , so sign is , and adds two negative numbers, giving a equivalent to at the original scale. q / a is and c / q is , both to full precision, and sorting returns .
The full solution is poly.py.
Why this design
Section titled “Why this design”horner does multiplications and additions per point, the minimum for a general polynomial, with extra memory per point. Computing each separately costs more multiplications and rounds more, and is no more accurate. It does not use numpy’s polyval, because np.polyval takes descending coefficients, the opposite of the convention that the Taylor-series and expf sections share; a hand-written loop also maps one-to-one onto the C loop in tl_expf.
For the quadratic, one could evaluate the textbook formula in extended precision instead. That only postpones the problem to larger , is not available in the C port, and costs more; the rewrite is exact algebra and fixes the cancellation at every scale. Likewise, testing for large and switching formulas would need a threshold, whereas scaling by a power of two always works and is exact.
Two tradeoffs are accepted. Scaling by the largest coefficient can underflow a coefficient more than about 600 orders of magnitude smaller: has no real roots, but its scaled underflows to 0 and the function returns . No caller has coefficients spanning that range. And the stable formula does not make itself accurate: for nearly double roots () the discriminant cancels and the roots keep only about half their digits. That is the ill-conditioning of the problem, not of the formula; Kahan’s notes, listed under Further reading, compute in extra precision.
What can go wrong
Section titled “What can go wrong”A correct implementation must pass the following checks, each tied to something that depends on it:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the hand-worked Horner example | unit | , and at 0, 1, | everyone agrees on the order |
| the hand-worked quadratics | unit | , and to float64 precision | the cancellation case by hand |
| ascending coefficients | boundary | is 1, is , at 3 is 29 | the Taylor and expf sections store coefficients ascending |
| exact on integer polynomials | property | random integer polynomials agree with Python’s exact integers | no rounding when nothing needs rounding |
| within Horner’s error bound | property | real coefficients stay within $\gamma_{2n}\sum | c_k |
| reference polynomials | golden | Taylor polynomials of and and against mpmath | the polynomials later sections evaluate |
| input shapes | boundary | scalars, 2-D arrays, float32 input, no coefficients, one coefficient | called on whole arrays of points |
| quadratics that cancel | golden | 15 quadratics with against mpmath at 80 digits | both roots right to float64 precision |
| boundary | and give | ||
| special roots | unit | a zero root, a double root, , | the second root is |
| ascending roots | unit | for every sign pattern | callers rely on the order |
| Vieta’s relations | property | and on 200 random quadratics | an independent check of both roots |
| huge | boundary | gives | scaling before squaring |
| non-quadratics | boundary | , , NaN, and infinity raise ValueError | errors, not NaN pairs |
The mistake that motivates the whole second half deserves a call-out.
Warning: The textbook formula makes the small root of 25% wrong, and with the small root comes out as 0. Compute only , which adds numbers of the same sign, and take the other root from Vieta.
Reading the coefficients in descending order, the np.polyval convention, makes evaluate and reverses every Taylor polynomial; the solution iterates reversed(c) over ascending storage. Treating as 0 makes return or divide by zero; the solution writes sign = 1.0 if b >= 0.0 else -1.0. Squaring unscaled makes return ; the solution scales all three coefficients by with frexp and ldexp. Taking the second root as is correct only when , so comes out wrong; Vieta’s is right for any . And returning the roots in the order computed gives whenever , so the pair is sorted before it is returned.
Where this leads
Section titled “Where this leads”Taylor series evaluates the range-reduced Taylor polynomial of in exp_range_reduced with horner, and Polynomial approximation and expf ports that code to C as tl_expf: range reduction, then a degree-5 or 6 polynomial by the same Horner loop, accurate to within 4 ulp. The stable rewrite of a formula that cancels, which this section starts, is the theme of Stable numerics, with logsumexp, softmax, and compensated sums.
Further reading
Section titled “Further reading”- OpenStax, College Algebra 2e (free), chapter 5 on polynomial functions.
- Higham, Accuracy and Stability of Numerical Algorithms, chapter 5, for Horner’s error bound.
- Press et al., Numerical Recipes, section 5.6, on quadratic and cubic equations, with the same trick.
- Kahan, “On the Cost of Floating-Point Computation Without Extra-Precise Arithmetic” (2004), on computing extra-precisely for nearly double roots.
- Cephes
polevlandp1evl(polevl.c): the Horner loop behind many C math libraries, with descending coefficients and an implicit leading 1. - musl and glibc
expf(muslsrc/math/expf.c): a short polynomial after range reduction, evaluated with Estrin-style pairing for instruction-level parallelism. numpy.polynomial.polynomial.polyval(numpynumpy/polynomial/): ascending coefficients like the solution’s, plus fitting, roots, and Chebyshev bases.
Key terms
Section titled “Key terms”- Polynomial: , stored in this book as its coefficient list in ascending order of power.
- Root: a number with ; by the factor theorem, then divides .
- Horner’s rule: evaluating from the inside out, with multiplications and additions.
- Discriminant: , whose sign decides whether a quadratic has two, one, or no real roots.
- Vieta’s formulas: and .
- Catastrophic cancellation: losing most significant digits by subtracting two nearly equal rounded numbers.
- Stable quadratic formula: with roots and , which never subtracts nearly equal numbers.
Summary
Section titled “Summary”- A polynomial is its list of coefficients; this book stores them in ascending order of power, so
coeffs[k]multiplies . - Horner’s rule evaluates a degree- polynomial with multiplications and additions by nesting, and its error is bounded by .
- On integer coefficients and points it is exact as long as every partial result stays below .
- The textbook quadratic formula cancels when , and the small root comes out with few or no correct digits. Computing and the roots and never subtracts nearly equal numbers.
- Two edge cases break naive code: must count as , and overflows for unless the coefficients are scaled first.
Review questions
Section titled “Review questions”- Why does
hornerstart withacc = 0rather thanacc = c[n]?Answer
The first iteration computes $0 \cdot x + c_n = c_n$ exactly, so starting from 0 gives the same result without indexing the last element. It also makes the empty coefficient list return zeros of the right shape, and buildsaccwith the shape ofxfrom the start, so scalars and arrays take the same path. - Why does the stable formula compute the second root as and not ?
Answer
Vieta's product is $x_1 x_2 = c/a$, so $x_2 = c/(a x_1)$. With $x_1 = q/a$, that is $c/q$. Writing $c/x_1$ drops the factor $a$ and is right only when $a = 1$: for $2x^2 - 10x + 12$, $q = 6$, $x_1 = 3$, and $c/x_1 = 4$ instead of the correct $c/q = 2$. - What goes wrong with
np.sign(b)in place of the explicit1.0 if b >= 0.0 else -1.0?Answer
np.sign(0.0)is 0, so for $b = 0$ the formula becomes $q = -\tfrac12(0 + 0 \cdot \sqrt D) = 0$, and $c/q$ divides by zero for any equation like $x^2 - 4$. Taking $+1$ gives $q = -\tfrac12\sqrt{16} = -2$ and the roots $q/a = -2$ and $c/q = 2$. - Why scale by a power of two, and why does the code not need to scale the roots back?
Answer
Multiplying by $2^{-e}$ changes only the exponent field, so $a$, $b$, $c$ are scaled with no rounding error, and the scaled equation has exactly the same roots. Both root formulas are ratios, $q/a$ and $c/q$, where $q$ is linear in the coefficients, so the scale factor cancels and the roots come out at the original scale. - Horner’s rule is exact on integer inputs while partial results stay below . Why does that bound matter, and why is the relative error large near a root even though Horner’s rule is “accurate”?
Answer
Every integer up to $2^{53}$ is a float64, so whileacc * x + cstays in that range neither operation rounds. Near a root, the result is a small difference of large terms; Horner's error bound is proportional to $\sum |c_k||x|^k$, the size of those terms, not to $|p(x)|$. A small absolute error divided by a near-zero value is a large relative error, and that comes from the polynomial's conditioning, so no evaluation order removes it. - Using Horner’s rule as synthetic division, divide by .
Answer
Run Horner at $x = 1$ over the coefficients from highest to lowest, $1, -6, 11, -6$: the accumulator goes $1$, $1 \cdot 1 - 6 = -5$, $-5 \cdot 1 + 11 = 6$, $6 \cdot 1 - 6 = 0$. The intermediate values $1, -5, 6$ are the quotient $x^2 - 5x + 6$, and the final 0 is the remainder $p(1)$, confirming that 1 is a root.