Exercise 1.29 of SICP

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 $$\frac{h}{3}[y_0+4y_1+2y_2+4y_3+2y_4+ \cdots + 2y_{n-2} + 4y_{n-1} + y_n]$$ where $$h=\frac{b-a}{n}$$, for some even integer n, and $$y_k = 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 (cube x) (* x x x))
(define (simpson-integral f a b n)
(define h (/ (- b a) n))
(define (next k) (+ k 1))
(define (coeff k)
(cond ((or (= k 0) (= k n)) 1)
((even? k) 2)
(else 4)))
(define (term k)
(* (coeff k) (f (+ a (* k h)))))
(* (/ h 3.0)
(sum term 0 next n)))

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


There are several things I want to note here. All the auxiliary functions to represent the leading coefficients as well as h make life a lot easier. It’s also important to note that the variables a and b in sum are not performing the same role as in the integral example earlier. In this case they are just counting indices from a = 0 to b = n. It might not be immediately obvious: When the function term is called from sum a_(the start of the integrating interval) is bound to it from the original call to simpson-integral, term only receives the index which it promptly evaluates.