习题1.29 (积分方法的优化---simpson规则)

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

(define (integral f a b dx)  ;积分
  (define (add-dx x) (+ x dx))
  (* (sum f (+ a (/ dx 2.0)) add-dx b)
     dx))

  (define (cube x) (* x x x))
  
(integral cube 0 1 0.0001)



(define (simpson f a b n)
  
  (define h (/ (- b a) n))

(define (y k)
  (f (+ a (* k h))))

(define (factor k)
  (cond ((or (= k 0) (= k n)) 1)
        ((odd? k) 4)
        (else 2)))
  
(define (term k)
  (* (factor k) (y k)))

(define (next k)
  (+ k 1))

(if (not (even? n))
    (error "n can't be odd")
    (* (/ h 3)
       (sum term (exact->inexact 0) next n))))

(simpson cube 0 1 100)

  

0.24999999874993412
0.24999999999999992

  

posted @ 2017-11-24 23:26  R4mble  阅读(184)  评论(0编辑  收藏  举报