Polynomial evaluation

A lot of functions are polynomials.

f(x) = x3 + 5x2 + 2x + 4

If we write this in C, we get a formula something like this:

x*x*x + 5*x*x + 2*x + 4

Many operations. We could use pow() for x3, but that's not going to help; it's probably slower.

Consider instead a factoring:

((x + 5) * x + 2) * x + 4

This is significantly fewer operations.

Also, the factoring doesn't require as much analysis as it might look; this computation is easily written in a loop in C for an arbitrary array of coefficients.

int i;
double sum = 0;
for (i = deg; i >= 0; i--)
    sum = sum * x + coeff[i];
Here coeff[i] is the coefficient of xi (e.g. coeff[0] is the un-multiplied-by-x term) and deg is the degree of the polynomial (i.e. the coeff array has subscripts from 0 to deg inclusive).
For example, the array for the earlier polynomial would be coeff[3] = 1, coeff[2] = 5, coeff[1] = 2, coeff[0] = 4.

This is, in fact, the standard way to evaluate polynomials. It also illustrates a general principle: that a little rearrangement of the way we think of something in mathematics can sometimes make something much easier to compute.


[list of topics covered, evening section]
[course notes available (evening section)]
[main course page]