小池有话说

SICP练习题1.29

2014-08-07

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 h = (b - a)/n, for some even integer n, and yk = 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.


中间的那个列表可以拆成三个列表

\[ y_0+y_1+y_2+…+y_{n-1} +y_n \]

\[ y_1+y_2+y_3…+y_{n-2} +y_{n-1} \]

\[ 2y_1+2y_3+2y_5…+2y_{n-3} +2y_{n-1} \]

于是,我们可以写出程序

(define (integral f a b n)
  (define h (/ (- b a) n))
  (define (f-next x) (+ x h))
  (define (f-next-2 x) (+ x h h))
  (/ (* h
    (+ (sum f (+ a h) f-next (- b h))
       (sum f a f-next b)
       (* 2 (sum f (+ a h) f-next-2 (- b h)))))
     3.0))