Skip to content

Instantly share code, notes, and snippets.

@BaseCase
Created September 13, 2008 15:47
Show Gist options
  • Save BaseCase/10607 to your computer and use it in GitHub Desktop.
Save BaseCase/10607 to your computer and use it in GitHub Desktop.
;Exercise 1.29- Define a procedure that uses Simpson's Rule to compute the integral
; of a function. Also, compare this proc with another one in the text.
;to do this one, we need the cube procedure from the text:
(define (cube x)
(* x x x))
;and also the sum procedure:
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))
;and we're going to compare the results to this integral proc:
(define (integral f a b dx)
(define (add-dx x) (+ x dx))
(* (sum f (+ a (/ dx 2.0)) add-dx b)
dx))
(define (inc x)
(+ x 1))
;here's the exercise: define an integral-computing proc based on Simpson's rule:
(define (simpson f a b n)
(define h (/ (- b a) n))
(define (y k) (f (+ a (* k h))))
(define (elem x)
(cond ((or (= x 0) (= x n)) (y x))
((odd? x) (* 4 (y x)))
((even? x) (* 2 (y x)))))
(* (/ h 3) (sum elem 0 inc n)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment