1 {-# LANGUAGE NoImplicitPrelude #-}
2 {-# LANGUAGE RebindableSyntax #-}
4 module Integration.Trapezoid (
9 import Misc ( partition )
11 import NumericPrelude hiding ( abs )
12 import qualified Algebra.Field as Field ( C )
13 import qualified Algebra.RealField as RealField ( C )
14 import qualified Algebra.ToInteger as ToInteger ( C )
15 import qualified Algebra.ToRational as ToRational ( C )
18 -- | Use the trapezoid rule to numerically integrate @f@ over the
19 -- interval [@a@, @b@].
24 -- >>> trapezoid_1 f (-1) 1
28 -- >>> trapezoid_1 f (-1) 1
32 -- >>> trapezoid_1 f (-1) 1
36 -- >>> trapezoid_1 f (-1) 1
39 trapezoid_1 :: (Field.C a, ToRational.C a, Field.C b)
40 => (a -> b) -- ^ The function @f@
41 -> a -- ^ The \"left\" endpoint, @a@
42 -> a -- ^ The \"right\" endpoint, @b@
45 (((f a) + (f b)) / 2) * coerced_interval_length
47 coerced_interval_length = fromRational' $ toRational (b - a)
49 -- | Use the composite trapezoid rule to numerically integrate @f@
50 -- over @n@ subintervals of [@a@, @b@].
54 -- >>> import Algebra.Absolute (abs)
56 -- >>> let area = trapezoid 1000 f (-1) 1
57 -- >>> abs (area - (2/3)) < 0.00001
60 -- >>> import Algebra.Absolute (abs)
61 -- >>> let area = trapezoid 1000 sin 0 pi
62 -- >>> abs (area - 2) < 0.0001
65 trapezoid :: (RealField.C a,
70 => c -- ^ The number of subintervals to use, @n@
71 -> (a -> b) -- ^ The function @f@
72 -> a -- ^ The \"left\" endpoint, @a@
73 -> a -- ^ The \"right\" endpoint, @b@
76 sum $ map trapezoid_pairs pieces
78 pieces = partition n a b
79 -- Convert the trapezoid_1 function into one that takes pairs
80 -- (a,b) instead of individual arguments 'a' and 'b'.
81 trapezoid_pairs = uncurry (trapezoid_1 f)