n should be even
(define (simpson-integral f a b m)
(define n (* m 1.0))
(define step (/ (- b a) n))
(define (next x) (+ x (* 2 step)))
(* step
(/ 1.0 3.0)
(+ (f a)
(* 2
(sum (next a) ; even-indexed elements
(- b (* 2 step))
f
next))
(* 4
(sum (+ a step) ; odd-indexed elements
(- b step)
f
next))
(f b))))
This approach is somewhat ugly, the sequence is divided into even-indexed and odd-indexed, since I don't find a universal pattern.
Exercise 1.30
(define (sum-iter a b f next)
(define (iter a result)
(if (> a b)
result
(iter (next a)
(+ result (f a)))))
(iter a 0))
Exercise 1.31
Recursive one
(define (product a b term next)
(if (> a b)
1
(* (term a)
(product (next a) b term next))))
Iterative one
(define (product a b term next)
(define (iter a result)
(if (> a b)
result
(iter (next a)
(* result (term a)))))
(iter a 1))
Use product to define factorial.
(define (factorial n)
(product 1 n identity inc))
Compute PI with John Wallis's formula.
(define (wallis-term m)
(/ (* (* 2.0 m)
(+ (* 2.0 m) 2.0))
(square (+ (* 2.0 m) 1.0))))
(define (wallis-formula n)
(product 1.0 n wallis-term inc))
(* 4.0 (wallis-formula 10000))

0 comments:
Post a Comment