X-Git-Url: http://gitweb.michael.orlitzky.com/?a=blobdiff_plain;f=src%2FPiecewise.hs;h=59af066db58dcd3a424f12576b76e7ae6998adad;hb=cc6e96512831fd319a185b1f5ef513a19b69c853;hp=cf71d05a6615081f1fed399df8ee4a5c2716f00c;hpb=ac19cda8bbd1d4ff05673892b9566e6ca2b367ea;p=numerical-analysis.git diff --git a/src/Piecewise.hs b/src/Piecewise.hs index cf71d05..59af066 100644 --- a/src/Piecewise.hs +++ b/src/Piecewise.hs @@ -4,13 +4,16 @@ module Piecewise ( Piecewise(..), evaluate, evaluate', - from_intervals ) + from_intervals, + list_plot' ) where import qualified Algebra.Additive as Additive ( C ) +import qualified Algebra.Field as Field ( C ) import Control.Arrow ( first ) +import Misc ( partition ) import NumericPrelude -import qualified Prelude as P +import Prelude () -- | A predicate is basically a function that returns True or -- False. In this case, the predicate is used to determine which @@ -38,8 +41,8 @@ data Piecewise a = -- point and the result is returned wrapped in a 'Just'. If the -- point is outside of the domain, 'Nothing' is returned. evaluate :: Piecewise a -> a -> Maybe a -evaluate (Piecewise pieces) x = - foldl f Nothing pieces +evaluate (Piecewise ps) x = + foldl f Nothing ps where f (Just y) _ = Just y f Nothing (p,g) = if p x then Just (g x) else Nothing @@ -77,3 +80,27 @@ from_intervals = where f :: (a,a) -> Predicate a f (x1,x2) x = x1 <= x && x <= x2 + + +-- | Plot a piecewise function over an interval @(x0,x1)@ using +-- 'evaluate''. Return the result a list of @(x,y)@ tuples. +-- +-- Examples: +-- +-- >>> let p1 = ((-1,0), \x -> -x) :: ((Double,Double), Double->Double) +-- >>> let p2 = ((0,1), \x -> x) :: ((Double,Double), Double->Double) +-- >>> let ivs = [p1, p2] +-- >>> let pw = from_intervals ivs +-- >>> list_plot' pw (-2) 2 4 +-- [(-2.0,0.0),(-1.0,1.0),(0.0,-0.0),(1.0,1.0),(2.0,0.0)] +-- +list_plot' :: (Additive.C a, Field.C a) + => Piecewise a + -> a + -> a + -> Int + -> [(a,a)] +list_plot' pw x0 x1 subintervals = + [ (x, evaluate' pw x) | x <- nodes ] + where + nodes = x0 : (map snd $ partition subintervals x0 x1)