X-Git-Url: http://gitweb.michael.orlitzky.com/?a=blobdiff_plain;f=src%2FIntegration%2FTrapezoid.hs;h=807bbc5839cb70e303dbc47d1bbf986305780b19;hb=b32831b5dde3440b85cbef62f4c47fcce0ee974f;hp=5452a5e8a5fe70195cf3de6711934dadd8cb623d;hpb=c3905924154d9a8d56bdc57e2f36fe48b8524eef;p=numerical-analysis.git diff --git a/src/Integration/Trapezoid.hs b/src/Integration/Trapezoid.hs index 5452a5e..807bbc5 100644 --- a/src/Integration/Trapezoid.hs +++ b/src/Integration/Trapezoid.hs @@ -1,7 +1,20 @@ -module Integration.Trapezoid +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE RebindableSyntax #-} + +module Integration.Trapezoid ( + trapezoid, + trapezoid_1 ) where -import Misc (partition) +import Misc ( partition ) + +import NumericPrelude hiding ( abs ) +import qualified Algebra.Field as Field ( C ) +import qualified Algebra.RealField as RealField ( C ) +import qualified Algebra.ToInteger as ToInteger ( C ) +import qualified Algebra.ToRational as ToRational ( C ) + -- | Use the trapezoid rule to numerically integrate @f@ over the -- interval [@a@, @b@]. @@ -24,30 +37,37 @@ import Misc (partition) -- >>> trapezoid_1 f (-1) 1 -- 2.0 -- -trapezoid_1 :: (RealFrac a, Fractional b, Num b) +trapezoid_1 :: forall a b. (Field.C a, ToRational.C a, Field.C b) => (a -> b) -- ^ The function @f@ -> a -- ^ The \"left\" endpoint, @a@ -> a -- ^ The \"right\" endpoint, @b@ -> b -trapezoid_1 f a b = - (((f a) + (f b)) / 2) * (realToFrac (b - a)) - +trapezoid_1 f x y = + (((f x) + (f y)) / 2) * coerced_interval_length + where + coerced_interval_length = fromRational' $ toRational (y - x) :: b -- | Use the composite trapezoid rule to numerically integrate @f@ -- over @n@ subintervals of [@a@, @b@]. -- -- Examples: -- +-- >>> import Algebra.Absolute (abs) -- >>> let f x = x^2 -- >>> let area = trapezoid 1000 f (-1) 1 -- >>> abs (area - (2/3)) < 0.00001 -- True -- +-- >>> import Algebra.Absolute (abs) -- >>> let area = trapezoid 1000 sin 0 pi -- >>> abs (area - 2) < 0.0001 -- True -- -trapezoid :: (RealFrac a, Fractional b, Num b, Integral c) +trapezoid :: (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@