xing's Blog

Give me a place to stand on, and I'll move the earth.

A simple scheme program for numeric integration

A numerical integration program in scheme (tested with PLT Scheme)

(define (trapezoid1 f a b D)
  (letrec ((sum (lambda (s b ah h)
                  (if (< ah b)
                      (sum (+ s (f ah)) b (+ ah h) h)
                      (* s (/ h 2.)))))
           (step (lambda (T h)
                   (if (> h D)
                       (step (+ (/ T 2) (sum 0 b (+ a (/ h 2)) h)) (/ h 2))
                       T))))
    (step (* (- b a) (/ (+ (f a) (f b)) 2)) (- b a))))

(define (f x) (* x x))
(trapezoid1 f 0 1 0.00001)


(define (trapezoid2 f a b D)
  (letrec ((sum (lambda (s ah h)
                  (if (< ah b)
                      (sum (+ s (f ah)) (+ ah h) h)
                      (* s (/ h 2.)))))
           (step (lambda (T h)
                   (if (> h D)
                       (step (+ (/ T 2) (sum 0 (+ a (/ h 2)) h)) (/ h 2))
                       T))))
    (step (* (- b a) (/ (+ (f a) (f b)) 2)) (- b a))))

(define (f x) (* x (sqrt x)))
(trapezoid2 f 0 1 0.00001)


(define (trapezoid3 f a b D)
  (letrec ((step (lambda (T h)
                   (letrec ((sum (lambda (s ah)
                                   (if (< ah b)
                                       (sum (+ s (f ah)) (+ ah h))
                                       (* s (/ h 2))))))
                     (if (> h D)
                         (step (+ (/ T 2) (sum 0 (+ a (/ h 2)))) (/ h 2))
                         T)))))
    (step (* (- b a) (/ (+ (f a) (f b)) 2)) (- b a))))

(define (f x) (* x (sqrt x)))
(trapezoid3 f 0 1 0.00001)