1 module Integration.Trapezoid
4 import Misc (partition)
6 -- | Use the trapezoid rule to numerically integrate @f@ over the
7 -- interval [@a@, @b@].
12 -- >>> trapezoid_1 f (-1) 1
16 -- >>> trapezoid_1 f (-1) 1
20 -- >>> trapezoid_1 f (-1) 1
24 -- >>> trapezoid_1 f (-1) 1
27 trapezoid_1 :: (RealFrac a, Fractional b, Num b)
28 => (a -> b) -- ^ The function @f@
29 -> a -- ^ The \"left\" endpoint, @a@
30 -> a -- ^ The \"right\" endpoint, @b@
33 (((f a) + (f b)) / 2) * (realToFrac (b - a))
36 -- | Use the composite trapezoid rule to numerically integrate @f@
37 -- over @n@ subintervals of [@a@, @b@].
42 -- >>> let area = trapezoid 1000 f (-1) 1
43 -- >>> abs (area - (2/3)) < 0.00001
46 -- >>> let area = trapezoid 1000 sin 0 pi
47 -- >>> abs (area - 2) < 0.0001
50 trapezoid :: (RealFrac a, Fractional b, Num b, Integral c)
51 => c -- ^ The number of subintervals to use, @n@
52 -> (a -> b) -- ^ The function @f@
53 -> a -- ^ The \"left\" endpoint, @a@
54 -> a -- ^ The \"right\" endpoint, @b@
57 sum $ map trapezoid_pairs pieces
59 pieces = partition n a b
60 -- Convert the trapezoid_1 function into one that takes pairs
61 -- (a,b) instead of individual arguments 'a' and 'b'.
62 trapezoid_pairs = uncurry (trapezoid_1 f)