Exercise 1.29
This is the exercise in Sicp. Here, we a write a procedure to compute integrals using (Homer) Simpson’s rule.
The Question
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
where , for some even integer , and . (Increasing increases the accuracy of the ap
proximation.) Define a procedure that takes as arguments
, , , and and returns the value of the integral, com
puted using Simpson’s Rule. Use your procedure to inte
grate cube
between 0 and 1 (with and ),
and compare the results to those of the integral
procedure.
Things to do before starting
First of all, I cannot possibly dream of explaining what integrals are here. So, if you don’t know what they are, search for “integral calculus”. Here is a quick refresher of terminology:
- is starting point.
- is ending point.
- or delta x, is a really (infinitesimally) small change in x
- is “function of” and is a function in maths
How it would work in our program
What happens is simple:
is multiplied by the stuff in the brackets, where is . The stuff in brackets is if is 0 or equal to , if odd, and if is even. In each of those cases, is
One thing we could do is, we could find the sum of the stuff in the
parantheses using sum
. After we have found the answer, we would
multiply it by . In sum, we would term
each element.
So to conclude:
- Each element is:
- if k is 0 or equal to
- if even
- if odd
- We multiply the sum of elements by
Our Solution
I have split this to 2 parts - term
and simpons
term
We first need to know how to compute . However, since it will never change, we will store it as a variable :
(define h (/ (- b a)n))
Then we need to know how to compute :
(define (find-y k)
(f (+ a (* k h))))
We now need to find each element:
(define (find-element k)
(define (find-y)
(f (+ a (* k h))))
(* (cond ((or (= k 0) (= k n)) 1)
((even? k) 2)
((else 4))) (find-y)))
simpsons
Now that we have found what we would have in term
, we have to write
the simpsons
procedure.
Defining sum
This is rather simple. We just copy/paste the code the authors gave us.
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))
next
For next
we will increment. So:
(define (inc n)
(+ n 1))
The Whole thing:
Now that we have term
, next
and sum
defined, we have to define
simpsons
:
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))
(define (simpsons f a b n)
(define h (/ (- b a) n))
(define (find-element k)
(define (find-y)
(f (+ a (* k h))))
(* (cond ((or (= k 0) (= k n)) 1)
((odd? k) 4)
(else 2))
(find-y)))
(define (inc n)
(+ n 1))
(/ (* h (sum find-element 0 inc n)) 3))
Let’s run it :
(simpsons cube 0 1 100.00)
;Value: .24999999999999992
1 (user) => (simpsons cube 0 1 1000.00)
;Value: .2500000000000003
Quite clearly, Simpson’s Rule is more accurate than the integral formula the authors use previously.