-module Integration.Simpson
+{-# LANGUAGE NoImplicitPrelude #-}
+{-# LANGUAGE RebindableSyntax #-}
+
+module Integration.Simpson (
+ simpson,
+ simpson_1 )
where
-import Misc (partition)
+import Misc ( partition )
+import NumericPrelude hiding ( abs )
+import qualified Algebra.RealField as RealField ( C )
+import qualified Algebra.ToInteger as ToInteger ( C )
+import qualified Algebra.ToRational as ToRational ( C )
-- | Use the Simpson's rule to numerically integrate @f@ over the
-- interval [@a@, @b@].
-- >>> simpson_1 f (-1) 1
-- 0.0
--
+-- >>> import Algebra.Absolute (abs)
-- >>> let f x = x^2
-- >>> let area = simpson_1 f (-1) 1
-- >>> abs (area - (2/3)) < 1/10^12
-- >>> simpson_1 f 0 1
-- 0.25
--
-simpson_1 :: (RealFrac a, Fractional b, Num b)
+simpson_1 :: (RealField.C a, ToRational.C a, RealField.C b)
=> (a -> b) -- ^ The function @f@
-> a -- ^ The \"left\" endpoint, @a@
-> a -- ^ The \"right\" endpoint, @b@
simpson_1 f a b =
coefficient * ((f a) + 4*(f midpoint) + (f b))
where
- coefficient = (fromRational $ toRational (b - a)) / 6
+ coefficient = fromRational' $ (toRational (b - a)) / 6
midpoint = (a + b) / 2
--
-- Examples:
--
+-- >>> import Algebra.Absolute (abs)
-- >>> let f x = x^4
-- >>> let area = simpson 10 f (-1) 1
-- >>> abs (area - (2/5)) < 0.0001
-- Note that the convergence here is much faster than the Trapezoid
-- rule!
--
+-- >>> import Algebra.Absolute (abs)
-- >>> let area = simpson 10 sin 0 pi
-- >>> abs (area - 2) < 0.00001
-- True
--
-simpson :: (RealFrac a, Fractional b, Num b, Integral c)
+simpson :: (RealField.C a,
+ ToRational.C a,
+ RealField.C b,
+ ToInteger.C c,
+ Enum c)
=> c -- ^ The number of subintervals to use, @n@
-> (a -> b) -- ^ The function @f@
-> a -- ^ The \"left\" endpoint, @a@