Exercise 1.29

Imports: [[Chapter 1.3]] cube inc sum

Simpson's rule provides a more accurate method of numerical integration: $$ \begin{aligned} \int_{a}^{b}f \approx \frac{h}{3}[y_{0} + 4y_{1} + 2y_{2} + 4y_3 + 2y_4 + \dots + 2y_{n-2} + 4y_{n-1} + y_n]dx \ \text{where} \ \ \ \ h = \frac{b-a}{n} \ \ \ \ \text{and} \ \ \ \ \ y_k= f(a+kh) \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \end{aligned} $$ The even integer \(n\) controls the accuracy of the approximation.

(define (simpson f a b n)
  (let ((h (/ (- b a) n)))
    (define (term k)
      (* (f (+ a (* k h)))
         (if (or (= k 0) (= k n))
             1
             (+ 2 (* 2 (remainder k 2))))))
    (* h 1/3 (sum term 0.0 inc n))))

Simpson's rule gives an exact answer for \(\int_{0}^{1} x^3 dx\) when \(n = 2\):

(simpsone cube 0 1 2) => 0.25