使用python进行多项式求值



对给定x值的多项式求值。输入是x的系数和值列表。输出是多项式和评估值为x

这是一个不使用任何求幂运算符的选项:

def pol_eval(a, x):
result = 0
# for every n in 0..len(a)-1
for n, a_n in enumerate(a):
# compute x^n
x_power_n = 1
for i in range(n):
x_power_n *= x
# add a_n * x^n to the final result
result += a_n * x_power_n
return result

示例:

a = [1,2,0,3] # coefficients
x = 1.5
print(pol_eval(a, x)) # 14.125

您可以使用递归,思考如何写出多项式。你可以在维基百科上参考霍纳的方法。

def evaluate_poly(x, coefficients):
if len(coefficients) == 1:
return coefficients[0]
return coefficients[0] + evaluate_poly(x, coefficients[1:])*x
a = [1, 2, 0, 3]
x = 1.5
print(evaluate_poly(x, a)) # 14.125

您可以在循环中进行此操作,在循环中,您可以累积系数的乘积,每次迭代乘以x后,x的幂递增:

a      = [1,2,0,3]
x      = 1.5
result = 0
xPower = 1
for coeff in a:
result += coeff * xPower
xPower *= x
print(result) # 14.125 = 1 + 2x + 0x^2 + 3x^3 = 1 + 3 + 0 + 10.125

注意,这可以通过在系数列表中倒退并在添加系数之前将先前结果乘以x来进一步简化:

result = 0
for coeff in reversed(a):
result = coeff + result * x

最新更新