March 30, 2010 at 15:10 Tags Math , Python

Here's a general degree-n polynomial:

To evaluate such a polynomial using a computer program, several approaches can be employed.

The simplest, naive method is to compute each term of the polynomial separately and then add them up. Here's the Python code for it:

def poly_naive (A, x): p = 0 for i, a in enumerate (A): p += (x ** i) * a return p

A is an array of coefficients, lowest first, until .

This method is quite inefficient. It requires n additions (since there are n+1 terms to be added) and multiplications.

Iterative method It's obvious that there's a lot of repetitive computations being done by raising x to successive powers. We can make things much more efficient by simply keeping the previous power of x between iterations. This is the "iterative method": def poly_iter (A, x): p = 0 xn = 1 for a in A: p += xn * a xn *= x return p In this code xn is the current power of x . We don't need to raise x to a power on each iteration of the loop, a single multiplication suffices. It's easy to see that there are 2n multiplications and n additions for each computation. The algorithm is now linear instead of quadratic.