计算总和与累加
问题描述:
过程积聚的定义如下:计算总和与累加
(define (accumulate combiner null-value term a next b)
(if (> a b) null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
问题1:X^N ;解决方法:递归无累加
(define (expon x n)
(if (> n 0) (* x
(expon x (- n 1))
)
1))
问题2:X + X^2 + x^4 + x^6 + ... +,对给定n计算序列的前n个元素。
问题3:1 + x/1! + x^2/2! + ... + x^n/n !;计算的总和为给定的x,正 可能不正确的解决方案:
(define (exp1 x n)
(define (term i)
(define (term1 k) (/ x k))
(accumulate * 1 term1 1 1+ i))
(accumulate + 0 term 1 1+ n))
为什么以前的代码是不正确:
(EXP1 0 3) - > 0;它应该是1 (exp1 1 1) - > 1;它应该是2
答
首先,我要说的是,你的EXP1过程在过低的水平在积累方面所规定的工作,并为敏锐的缘故改写它,而不是资金和阶乘方面:
(define (sum term a b) (accumulate + 0 term a 1+ b)) (define (product term a b) (accumulate * 1 term a 1+ b)) (define (identity x) x) (define (fact n) (if (= n 0) 1 (product identity 1 n))) (define (exp1 x n) (define (term i) (/ (expon x i) (fact i))) (sum term 1 n))
现在你的问题:你得到(EXP1 0 3)
→0的理由并不比你忘了在系列的开始添加1更多的,只是将自己计算的x/1! + x^2/2! + ... + x^n/n!
更改EXP1包括缺少长期按预期工作:
(define (exp1 x n) (define (term i) (/ (expon x i) (fact i))) (+ 1 (sum term 1 n))) => (exp1 0 3) 1 => (exp1 1 1) 2