2.34
练习 2.34 对于x的某个给定值,求出一个多项式在x值,也可以形式化为一种累积。假定需要求下面多项式的值:
采用著名的Horner规则,可以构造出下面的计算:
换名话说,我们可以从an开始,乘以x,再加上,乘以x,如此下去,直到处理完。请填充下面的模板,做出一个复用Horner规则求多项式值的过程。假定多项式的系数安排在一个序列里,从直至。
(define (horner-eval x coefficient-sequence)
(accumulate (lambda (this-coeff higher-terms) <??>)
0
coefficient-sequence))
例如,为了计算在x=2的值,你需要求值:
(horner-eval 2 (list 1 3 0 5 0 1))
首先,定义 accumulate
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))
)
)
(define (horner-eval x coefficient-sequence)
(accumulate (lambda (this-coeff higher-terms) (+ this-coeff (* higher-terms x)))
0
coefficient-sequence))
(horner-eval 2 (list 1 3 0 5 0 1))
对比: