天天看点

SICP 1.29-1.33

通用求和过程

(define (sum term a next b)
  (if (> a b)
      
      (+ (term a)
         (sum term (next a) next b))))
           
下面几题答案,非本人解答,有待验证

练习1.29

函数f在范围a和b之间的定积分的近似值

(h/3)[y  0   + 4y  1   + 2y  2   + 4y  3   + 2y  4   + …… + 2y  n−2   + 4y  n−1   + y  n   ]

h = (b - a) / n, n为某个偶数

y  k   = f  <script id="MathJax-Element-360" type="math/tex">f</script>(a + kh) 增大n能提高近似值的精度

(define (si f a b n)
  (let ((h (/ (- b a) n)))
    (define (next x)
      (+ x ))
    (define (yk k)
      (f (+ a (* k h))))
    (* (+ (sum yk  next (- n ))
          (yk )
          (yk n))
       (/ h ))))

(define (sum term a ne b)
  (if (> a b)
    
    (+ (* (if (even? a)  )
          (term a))
       (sum term (ne a) ne b))))
           

练习1.30

(define (si f a b n)
  (let ((h (/ (- b a) n)))
    (define (next x)
      (+ x ))
    (define (yk k)
      (f (+ a (* k h))))
    (* (+ (sum yk  next (- n ))
          (yk )
          (yk n))
       (/ h ))))

(define (sum term a ne b)
  (define (iter c result)
    (if (> c b)
      result
      (iter (ne c) (+ result (* (if (even? c)  ) (term c))))))
  (iter a ))

(define (cube x)
  (* x x x))
           

练习1.31

(define (product term a next b)
  (if (> a b)
    
    (* (term a)
       (product term (next a) next b))))

(define (factorial n)
  (define (te x)
    x)
  (define (ne x)
    (+ x ))
  (product te  ne n)) 

(define (pi n)
  (define (te x)
    (/ (* (- x ) (+ x ))
       (* x x)))
  (define (ne x)
    (+ x ))
  (* (product te  ne (+ n ))
     ))
           

练习1.32

(define (accumulate_r combiner null-value term a next b)
  (if (> a b)
    null-value
    (combiner (term a)
              (accumulate_r combiner null-value term (next a) next b))))

(define (accumulate_i combiner null-value term a next b result)
  (if (> a b)
    result
    (accumulate_i combiner null-value term (next a) next b (combiner result (term a)))))

(define (sum term a next b)
  (define (plus x y)
    (+ x y))
  (accumulate_r plus  term a next b))

(define (product term a next b)
  (define (multiply x y)
    (* x y))
  (accumulate_i multiply  term a next b ))
           

练习1.33

(define (filtered-accumulate_r combiner null-value term a next b f) 
   (if (> a b) 
     null-value 
     (if (f a) 
       (combiner (term a) 
                 (accumulate_r combiner null-value term (next a) next b f)) 
       (accumulate_r combiner null-value term (next a) next b f)))) 

(define (sum-of-squres-of-prime a b) 
   (define (combiner x y) 
     (+ x y)) 
   (define (term x) 
     (* x x)) 
   (define (next x) 
     (+ x )) 
   (filtered-accumulate_r combiner  term a next b prime?)) 


(define (product-of-primes-to-n n) 
   (define (combiner x y) 
     (* x y)) 
   (define (term x) 
     x) 
   (define (next x) 
     (+ x )) 
   (define (prime-to-n? x) 
     (= (gcd x n) )) 
   (filtered-accumulate_r combiner  term a next b prime-to-n?))
           

继续阅读