-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathex1-29-simpsons-rule-with-sum-iter.scm
44 lines (36 loc) · 1.23 KB
/
ex1-29-simpsons-rule-with-sum-iter.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
; Ex. 1.29 Simpsons Rule for numerical integration
; DID NOT PEEK!!!!!! MY LOGIC WORKED THE FIRST TIME!!!!!!!!
; SO GLAD I did NOT peek :)))
(define (simpsons-rule f a b n)
; n must always be even
(define n-even
(if (even? n) n (+ n 1)))
; h is the smallest increment
(define h
(/ (- b a) n-even))
; Apply the correct multiplier to each yk to create
; a single summable term
(define (term x)
(* (cond ((= (/ x h) n-even) 1.0)
((even? (/ x h)) 2.0)
(else 4.0))
(f (+ a x))))
; The transform that 'sum' uses to increment each new yk term
(define (next m)
(+ m h))
; Invoke the computation using the 'sum' procedure. Note that
; the 0-th term is added as the logic starts computing from
; the 1-st term.
(if (<= n 0)
"Cannot compute"
(* (/ h 3.0) (+ (f a) (sum term h next (- b a))))))
; Sum of series limited by x and y
; ; Re-implemented to compute by iterative process (see Ex. 1.30)
(define (sum term x next y)
(define (iter x result)
(if (> x y)
result
(iter (next x) (+ result (term x)))))
(iter x 0))
(define (even? x)
(= (remainder x 2) 0))