sicp-ex-1.29


 (define (round-to-next-even x) 
   (+ x (remainder x 2))) 
 (define (simpson f a b n) 
   (define fixed-n (round-to-next-even n)) 
   (define h (/ (- b a) fixed-n)) 
   (define (simpson-term k) 
     (define y (f (+ a (* k h)))) 
     (if (or (= k 0) (= k fixed-n)) 
         (* 1 y) 
         (if (even? k) 
             (* 2 y) 
             (* 4 y)))) 
   (* (/ h 3) (sum simpson-term 0 inc fixed-n))) 

This is a similar solution, complete with testing code. There is no rounding of n to the next even number, because the exercise assumes n to be even.

 ;; ex 1.29 
  
 (define (cube x) (* x x x)) 
  
 (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-integral f a b n) 
   (define h (/ (- b a) n)) 
   (define (yk k) (f (+ a (* h k)))) 
   (define (simpson-term k) 
     (* (cond ((or (= k 0) (= k n)) 1) 
              ((odd? k) 4) 
              (else 2)) 
        (yk k))) 
   (* (/ h 3) (sum simpson-term 0 inc n))) 
  
 ;; Testing 
 (simpson-integral cube 0 1 100) 
 (simpson-integral cube 0 1 1000) 

There is a third way which approaches the solution by breaking the problem into four parts: (f y0), (f yn) and two sums,one over even k and another over odd k

  
 (define (another-simpson-integral f a b n) 
   (define h (/ (- b a) n))  
   (define (add-2h x) (+ x (* 2 h))) 
   (* (/ h 3.0) (+ (f a)  
                   (* 4.0 (sum f (+ a h) add-2h (- b h)))  
                   (* 2.0 (sum f (add-2h a) add-2h (- b h)))  
                   (f (+ a (* h n)))))) 

<< Previous exercise (1.28) | sicp-solutions | Next exercise (1.30) >>