Created
March 26, 2010 19:01
-
-
Save flatline/345252 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang scheme | |
;some quick code for approximating definite integrals | |
;Trapezoid Rule approximation for the integral of f over range (a,b) in n divisions | |
(define (area-trap f a b n) | |
(let ([dx (/ (- b a) n)]) | |
(define (iter x list) | |
(cond ((= x b) | |
(iter (- x dx) (cons (f x) list))) | |
((= x a) | |
(cons (f x) list)) | |
(else | |
(iter (- x dx) (cons (* 2 (f x)) list))))) | |
(* (/ dx 2) (foldl + 0 (iter b '()))))) | |
;Simpson's rule approximation for the integral of f over range (a,b) in n divisions | |
(define (area-simps f a b n) | |
(let ([dx (/ (- b a) n)]) | |
(define (iter x count list) | |
(cond ((= x b) | |
(iter (- x dx) (- count 1) (cons (f x) list))) | |
((= x a) | |
(cons (f x) list)) | |
((odd? count) | |
(iter (- x dx) (- count 1) (cons (* 4 (f x)) list))) | |
(else | |
(iter (- x dx) (- count 1) (cons (* 2 (f x)) list))))) | |
(* (/ dx 3) (foldl + 0 (iter b n '()))))) | |
;Midpoint Rule approximation for the integral of f over range (a,b) in n divisions | |
(define (area-mid f a b n) | |
(let ([dx (/ (- b a) n)]) | |
(define (iter x list) | |
(let ([midp (- x (/ dx 2))]) | |
(cond ((= x (+ a dx)) | |
(cons (f midp) list)) | |
(else | |
(iter (- x dx) (cons (f midp) list)))))) | |
(* dx (foldl + 0 (iter b '()))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment