Evaluating a polynomial looks too simple to need an algorithm, but the obvious way wastes work. Synthetic division already contains a better way: the remainder of dividing $p(x)$ by $x - c$ is $p(c)$, and the steps of synthetic division are exactly Horner's method.
Factor $x$ out again and again: $$a_3x^{3} + a_2x^{2} + a_1x + a_0 = ((a_3x + a_2)x + a_1)x + a_0.$$ Start with $b = a_n$, then for $k = n - 1$ down to $0$ replace $b$ by $bx + a_k$. The last $b$ is $p(x)$.
Key idea
Why it works
Worked example: Evaluating a cubic
- Coefficients from the top: $2, -6, 2, -1$. Start with $b = 2$.
- $b = 2 \cdot 3 - 6 = 0$.
- $b = 0 \cdot 3 + 2 = 2$.
- $b = 2 \cdot 3 - 1 = 5$. So $p(3) = 5$ (check: $54 - 54 + 6 - 1 = 5$).
Answer: $5$
Worked example: A missing power
- There is no $x^{3}$ term, so the coefficients are $1, 0, -3, 1, -2$.
- $b$: $1 \to 1(-2) + 0 = -2 \to (-2)(-2) - 3 = 1 \to 1(-2) + 1 = -1 \to (-1)(-2) - 2 = 0$.
- $p(-2) = 0$, so $x = -2$ is a root. Leaving out the $0$ would have evaluated a different polynomial.
Answer: $0$
| coefficient | $2$ | $-6$ | $2$ | $-1$ |
|---|---|---|---|---|
| $b$ (at $x = 3$) | $2$ | $0$ | $2$ | $5$ |
Worked example: The derivative for free
- $p(x) = (x - 3)q(x) + p(3)$ with $q(x) = 2x^{2} + 0x + 2$.
- Differentiate: $p'(x) = q(x) + (x - 3)q'(x)$, so $p'(3) = q(3)$.
- A second Horner pass on $2, 0, 2$: $b = 2 \to 2 \cdot 3 + 0 = 6 \to 6 \cdot 3 + 2 = 20$. Check: $p'(x) = 6x^{2} - 12x + 2$ gives $54 - 36 + 2 = 20$.
Answer: $p'(3) = 20$
In code the whole method is two lines: set b = a[n], then for k = n - 1 down to 0 set b = b*x + a[k]. Each pass through the loop does one rounding in the multiply and one in the add, so the computed value is close to the exact value of a polynomial whose coefficients have been changed only slightly: Horner's method is backward stable.
Common mistake