SICP 全笔记

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

fix this

$$\frac{h}{3}\[y_0+4y_1+2y_2+4y_3+2y_4+\dots+2y_{n-2}+4y_{n-1}+y_n\] $$ 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.

我们可以将公式写为更有规律的式子

$$\begin{aligned} & \frac{h}{3}\[y_0+4y_1+2y_2+4y_3+2y_4+\dots+2y_{n-2}+4y_{n-1}+y_n\] \\ = & \frac{h}{3}\[y_0 + y_n + 4\(y_1 + y_3 + \dots\) + 2\(y_2 + y_4+\dots\)\] \\ = & \frac{h}{3}\[f(a)+f(a+nh)+4\(f(a+h)+f(a+3h)+\dots\)+2\(f(a+2h)+f(a+4h)+\dots\)\] \\ \end{aligned} $$ 然后我们可以如下编写程序

(define (sum term a next b)
  (if (> a b)
      0
      (+ (term a)
         (sum term (next a) next b))))


(define (simpson-rule f a b n)
  (let ((h (/ (- b a) n)))  
    (define (next t)
      (+ h h t))
    (* (/ h 3.0)
       (+ (f a)
          (f b)
          (* 4.0 (sum f (+ a h) next (+ a (* h (- n 1)))))
          (* 2.0 (sum f (+ a h h) next (+ a (* h (- n 2)))))))))

;;; tests begin
(define (cube x)
  (* x x x))

(simpson-rule cube 0 1 100) ; ;Value: .25

(simpson-rule cube 0 1 1000) ; ;Value: .25