Numerical integration: Difference between revisions

(Added Racket version)
Line 3,260:
(define (trapezium f x h) (/ (+ (f x) (f (+ x h))) 2))
(define (simpson f x h) (/ (+ (f x) (* 4 (f (+ x (/ h 2)))) (f (+ x h))) 6))
 
(define (squaretest x)f (*a xb x)s n)
(displayln n)
(for ([meth (list left-rect mid-rect right-rect trapezium simpson)]
(integrate square 0 1 10 left-rect)
[name '( left-rect mid-rect right-rect trapezium simpson)])
(integrate square 0 1 10 mid-rect)
(displayln (~a name ":\t" (integrate squaref 0a 1b 10s right-rectmeth))))
(newline))
(integrate square 0 1 10 trapezium)
 
(integrate square 0 1 10 simpson)
(test (λ(x) (* x x x)) 0. 1. 100 "CUBED")
(test (λ(x) (/ x)) 1. 100. 1000 "RECIPROCAL")
(test (λ(x) x) 0. 5000. 5000000 "IDENTITY")
(test (λ(x) x) 0. 6000. 6000000 "IDENTITY")
</lang>
Output:
<lang racket>
CUBED
77/200
left-rect: 0.25502500000000006
1771/4000
mid-rect: 0.26013825125000006
253/500
right-rect: 0.26532801000000006
891/2000
trapezium: 0.260176505
1331/3000
simpson: 0.2601510025
 
RECIPROCAL
left-rect: 4.65598105751468
mid-rect: 4.605752058870831
right-rect: 4.557970078384019
trapezium: 4.606975567949346
simpson: 4.606159895230326
 
IDENTITY
left-rect: 12500002.5
mid-rect: 12500005.0000005
right-rect: 12500007.500001
trapezium: 12500005.0000005
simpson: 12500005.0000005
 
IDENTITY
left-rect: 18000003.000000004
mid-rect: 18000006.00000049
right-rect: 18000009.000001002
trapezium: 18000006.00000049
simpson: 18000006.00000049
</lang>
 
Anonymous user