my attempt to do the exercises in sicp.

Sunday, June 29, 2008

sicp exercise 1.29



;  Exercise 1.29. Simpson's Rule is a more accurate method of numerical integration than the method
;  illustrated above. Using Simpson's Rule, the integral of a function f between a and b is approximated
;  as
;
;  h(y[0] + 2y[1] + 4y[2] + 2y[3] + ...... 2y[n-2] + 4y[n-1] + y[n])/3
;
;  where h = (b - a)/n, for some even integer n, and yk = f(a + kh). (Increasing n increases the
;  accuracy of the approximation.) Define a procedure that takes as arguments f, a, b, and n and returns
;  the value of the integral, computed using Simpson's Rule. Use your procedure to integrate cube between
;  0 and 1 (with n = 100 and n = 1000), and compare the results to those of the integral procedure
;  shown above.


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

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

(define (integrate func a b n)
   (define h (/ (- b a) n))
   (define (next x) (+ x h))
   (define (prefix x)
      (cond ((even? (/ (- x a) h)) 4)
            (else 2)))
   (define (term x) (* (prefix x) (func x)))
   (/
      (*
         (+
            (func a)
            (func b)
            (sum-iter term next (+ a h) (- b h)))
         h)
       3))

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

(display (integrate cube 0 1  100))(newline)
(display (integrate cube 0 1 1000))(newline)
                                                

No comments: