1.29 Exercise 1.29

This procedure computes integrals with Simpson’s rule:

(define (simpson-integral f a b n)
  (define h (/ (- b a) n))
  (define (term k)
    (let ((y (f (+ a (* k h)))))
      (cond ((= k 0) y)
            ((= k n) y)
            ((divides? 2 k) (* 2 y))
            (else (* 4 y)))))
  (* (/ h 3) (sum term 1 inc n)))

The decision that made this simplest to write was to let a and b in the sum be 1 and n-1, respectively – the indexes of the evaluated function values, rather than the values themselves. This way, we can test for what to multiply the value by (1, 2, or 4) by examining the index, rather than having to describe the rule using the sum of multiple summations or something else more complicated than this.

Comparing outputs with the book:

> (integral cube 0 1 0.01)

0.24998750000000042

> (integral cube 0 1 0.001)

0.249999875000001

> (simpson-integral cube 0 1 100.0)

0.24999999999999992

> (simpson-integral cube 0 1 1000.0)

0.2500000000000003