I'd recommend using numpy.poly1d
and numpy.polymul
, where the coefficients are a0*x2 + a1*x + a2
.
For example, to represent 3*x**2 + 2*x + 1
:
p1 = numpy.poly1d([3,2,1])
And with the resulting poly1d
object you can operate using *
, /
and so on...:
print(p1*p1)
# 4 3 2
#9 x + 12 x + 10 x + 4 x + 1
If you want to build your own functions, assuming that p contains the coefficients in order: a0 + a1*x + a2*x**2 + ...
:
def eval_polynomial(p,x):
return sum((a*x**i for i,a in enumerate(p)))
def multiply_by_one_term(p, a, k):
return [0]*k + [a*i for i in p]
Note
My evaluate function uses exponentials, which can be avoided with Horner's rule, as posted in another answer, which is available in Numpy's polyval
function