It seems you are describing numpy.polyval()
:
import numpy as np
# 1 * x**2 + 2 * x**1 + 3 * x**0
# computed at points: [0, 1, 2]
y = np.polyval([1, 2, 3], [0, 1, 2])
print(y)
# [ 3 6 11]
Note that the same could be achieved with np.poly1d()
, which should be more efficient if you are computing values from the same polynomial multiple times:
import numpy as np
# 1 * x**2 + 2 * x**1 + 3 * x**0
my_poly_func = np.poly1d([1, 2, 3])
# computed at points: [0, 1, 2]
y = my_poly_func([0, 1, 2])
print(y)
# [ 3 6 11]
If you want to use only Python built-ins, you could easily define a polyval()
version yourself, e.g.:
def polyval(p, x):
return [sum(p_i * x_i ** i for i, p_i in enumerate(p[::-1])) for x_i in x]
y = polyval([1, 2, 3], [0, 1, 2])
print(y)
# [3, 6, 11]
or, more efficiently:
def polyval_horner(p, x):
y = []
for x_i in x:
y_i = 0
for p_i in p:
y_i = x_i * y_i + p_i
y.append(y_i)
return y
y = polyval_horner([1, 2, 3], [0, 1, 2])
print(y)
# [3, 6, 11]
but I would recommend using NumPy unless you have a good reason not to (for example, if your result would overflow with NumPy but not with pure Python).