2010-06-29 290 views
0

過程積聚的定義如下:計算總和與累加

(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

回答

3

首先,我要說的是,你的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