Horner's rule
Evaluate a degree-n polynomial with only n multiplications and n additions, by factoring x out again and again.
Evaluating a_n·xⁿ + … + a_1·x + a_0 power by power takes O(n²) multiplications (or 2n if each power reuses the
last). Horner keeps factoring x out:
- Time:
O(n) - Space:
O(1) - CLRS, chapter 2
- Grimaldi, chapter 4
P(x) = 2x³ − 6x² + 2x − 1 at x = 3: three multiplications and three additions, giving 5.
def horner(coeffs, x):# coeffs holds one row: a_n, …, a_1, a_0 (the highest power first).y = 0rows = []for a in coeffs[0]:y = y * x + arows.append((a, y))return y
Start
y—
The table is still empty.
Local variables
x3
Orange = changed in this step
coeffs list
[2, -6, 2, -1]
Call stack
- horner()line 1
Step 1 of 17
Explanation
The idea
Evaluating a_n·xⁿ + … + a_1·x + a_0 power by power takes O(n²) multiplications (or 2n if each power reuses the
last). Horner keeps factoring x out:
2x³ − 6x² + 2x − 1 = ((2·x − 6)·x + 2)·x − 1
so only n multiplications and n additions are needed.
Uses
- Converting a number from any base to decimal (the "reading a binary number" input).
- Dividing a polynomial by
x − c(synthetic division): the intermediate values ofyare the quotient's coefficients.
What to watch in the trace
- Each table row is one coefficient and the value of
yafter it.