代码之家  ›  专栏  ›  技术社区  ›  user815693

用累加计算和

  •  0
  • user815693  · 技术社区  · 16 年前

    (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))
    

    问题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))
    

    为什么前面的代码不正确:

    (表达式1)—>1 ; 应该是2

    1 回复  |  直到 16 年前
        1
  •  3
  •   Nietzche-jou    16 年前

    首先,我要说的是,您的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
    
    推荐文章