sicp-1.31

Posted on 2015-02-14 08:22:48 +0900 in SICP Lisp

1.29

(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))

(define (integral f a b dx)
  (define (add-dx x) (+ x dx))
  (* (sum f (+ a (/ dx 2.0)) add-dx b)
     dx))

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

(integral cube 0 1 0.01)

(define (simpson-integral f a b n)
  (define h (/ (- b a) n))
  (define (next a) (+ a 1))
  (define (current k) (+ a
                         (* k h)))
  (define (simpson-term x)
    (define point (current x))
    (cond ((or (= x 0) (= x n)) (f point))
          ((even? x) (* 2
                        (f point)))
          (else (* 4
                   (f point)))))
  (* h
     (/ (sum simpson-term 0 next n)
        3)))

1.30

(define (sum-iter term a next b)
  (define (iter a result)
    (if (> a b)
      result
      (iter (next a) (+ result (term a)))))
  (iter a 0))

1.31

(define (pi-term a)
  (define norm (+ 1
                  (* 2 a)))
  (*
    (/ (-
         (square norm)
         1)
       (square norm))))

(define (wallis-pi n)
  (* 4.0
     (product pi-term 1 inc n)))

(define (product-iter term a next b)
  (define (iter a result)
    (if (> a b)
      result
      (iter (next a) (* result (term a)))))
  (iter a 1))

1.32

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

(define (sum term a next b)
  (accumulate + 0 term a next b))

(define (product term a next b)
  (accumulate * 1 term a next b))

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

1.33

(define (filtered-accumulate combiner null-value term a next b filter)
  (if (> a b) null-value
    (if (filter a)
      (combiner (term a) (filtered-accumulate combiner null-value term (next a) next b filter))
      (filtered-accumulate combiner null-value term (next a) next b filter))))
----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | sicp-126 »

Hide Comments

comments powered by Disqus