2007-07-17
算法学习:用Horner算法计算多项式求和
需求:
计算表达式,
a0 + a1 * x + a2 * x^2 + a3 * x^3 + ... + an * x^n
解法:
使用Horner算法解答:
原式 = a0 + x(a1 + x(a2 + x(a3 + ...x(an)...))
result <-- a[n]
i <-- n
while i >= 0
result <-- reslut * x + a[i]
i <-- i - 1
Python描述:
def Horner(a, n, x):
result = a[n]
i = n - 1
while i >= 0:
result = result * x + a[i]
i -= 1
return result
计算表达式,
a0 + a1 * x + a2 * x^2 + a3 * x^3 + ... + an * x^n
解法:
使用Horner算法解答:
原式 = a0 + x(a1 + x(a2 + x(a3 + ...x(an)...))
result <-- a[n]
i <-- n
while i >= 0
result <-- reslut * x + a[i]
i <-- i - 1
Python描述:
def Horner(a, n, x):
result = a[n]
i = n - 1
while i >= 0:
result = result * x + a[i]
i -= 1
return result