用累积计算总和

时间:2010-06-29 11:12:16

标签: scheme sum sequence

程序累积定义如下:

(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,n的总和 可能不正确的解决方案:

(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

1 个答案:

答案 0 :(得分:3)

首先,我会说你的EXP1程序在ACCUMULATE的定义中运行的程度太低,并且为了清晰度而不是用sums和factorials来重写它:

(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
相关问题