1 {-# LANGUAGE NoImplicitPrelude #-}
2 {-# LANGUAGE RebindableSyntax #-}
4 module Integration.Simpson (
9 import Misc ( partition )
11 import NumericPrelude hiding ( abs )
12 import qualified Algebra.RealField as RealField ( C )
13 import qualified Algebra.ToInteger as ToInteger ( C )
14 import qualified Algebra.ToRational as ToRational ( C )
16 -- | Use the Simpson's rule to numerically integrate @f@ over the
17 -- interval [@a@, @b@].
22 -- >>> simpson_1 f (-1) 1
26 -- >>> simpson_1 f (-1) 1
29 -- >>> import Algebra.Absolute (abs)
31 -- >>> let area = simpson_1 f (-1) 1
32 -- >>> abs (area - (2/3)) < 1/10^12
36 -- >>> simpson_1 f (-1) 1
40 -- >>> simpson_1 f 0 1
43 simpson_1 :: (RealField.C a, ToRational.C a, RealField.C b)
44 => (a -> b) -- ^ The function @f@
45 -> a -- ^ The \"left\" endpoint, @a@
46 -> a -- ^ The \"right\" endpoint, @b@
49 coefficient * ((f a) + 4*(f midpoint) + (f b))
51 coefficient = fromRational' $ (toRational (b - a)) / 6
52 midpoint = (a + b) / 2
55 -- | Use the composite Simpson's rule to numerically integrate @f@
56 -- over @n@ subintervals of [@a@, @b@].
60 -- >>> import Algebra.Absolute (abs)
62 -- >>> let area = simpson 10 f (-1) 1
63 -- >>> abs (area - (2/5)) < 0.0001
66 -- Note that the convergence here is much faster than the Trapezoid
69 -- >>> import Algebra.Absolute (abs)
70 -- >>> let area = simpson 10 sin 0 pi
71 -- >>> abs (area - 2) < 0.00001
74 simpson :: (RealField.C a,
79 => c -- ^ The number of subintervals to use, @n@
80 -> (a -> b) -- ^ The function @f@
81 -> a -- ^ The \"left\" endpoint, @a@
82 -> a -- ^ The \"right\" endpoint, @b@
85 sum $ map simpson_pairs pieces
87 pieces = partition n a b
88 -- Convert the simpson_1 function into one that takes pairs
89 -- (a,b) instead of individual arguments 'a' and 'b'.
90 simpson_pairs = uncurry (simpson_1 f)