http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_thm_1.29

I don't like this one, I want to see someone post a better version:

;Simpson's rule
;integral of f between a & b = h/3[y0 + 4y1 + 2y2 + 4y3 + ... + yn]
; h = (b-a)/n, yk = f(a + kh)
; endpoints multiplied by 1
; odd #s * 4, evens * 2.
(define (simpsons-rule f a b n)
  (let ((h (/ (- b a) n)))
    (define (coef k)
      (cond ((= 0 (modulo k 2)) 2) (else 4)))
    (define (term k) (* (coef k) (f (+ a (* k h)))))
    (define (next k) (+ k 1))
    (* (/ h 3)
       (+ (f a) ; y0
      (f b) ; yn
      (sum term 1 next (- n 1))))))

Here's mine.

Since we haven't been given let yet, I just defined another function to bind h. I also included inc as it was defined previously since it seemed useful here. We also defined the term differently, you defined the coefficient separately whereas I folded that into the term.

-inimino

; http://inimino.org/~inimino/projects/2009/SICP/chap_1/1.29.scm
 
(define (inc n) (+ n 1))
 
(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))
 
(define (simpson f a b n)
  (simpson-h f a b n (/ (- b a) n)))
 
(define (simpson-h f a b n h)
  (define (y k)
    (f (+ a (* k h))))
  (define (term k)
    (cond ((= k n)  (y k))
          ((= k 0)  (y k))
          ((odd? k) (* 4 (y k)))
          (else     (* 2 (y k)))))
  (* (/ h 3)
     (sum term 0 inc n)))
 
exercise_1.29.txt · Last modified: 2009/02/25 00:17 by 76.25.166.213
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki