1 -- | The Roots.Fast module contains faster implementations of the
2 -- 'Roots.Simple' algorithms. Generally, we will pass precomputed
3 -- values to the next iteration of a function rather than passing
4 -- the function and the points at which to (re)evaluate it.
9 has_root :: (Fractional a, Ord a, Ord b, Num b)
10 => (a -> b) -- ^ The function @f@
11 -> a -- ^ The \"left\" endpoint, @a@
12 -> a -- ^ The \"right\" endpoint, @b@
13 -> Maybe a -- ^ The size of the smallest subinterval
14 -- we'll examine, @epsilon@
15 -> Maybe b -- ^ Precoumpted f(a)
16 -> Maybe b -- ^ Precoumpted f(b)
18 has_root f a b epsilon f_of_a f_of_b =
19 if not ((signum (f_of_a')) * (signum (f_of_b')) == 1) then
20 -- We don't care about epsilon here, there's definitely a root!
23 if (b - a) <= epsilon' then
24 -- Give up, return false.
27 -- If either [a,c] or [c,b] have roots, we do too.
28 (has_root f a c (Just epsilon') (Just f_of_a') Nothing) ||
29 (has_root f c b (Just epsilon') Nothing (Just f_of_b'))
31 -- If the size of the smallest subinterval is not specified,
32 -- assume we just want to check once on all of [a,b].
33 epsilon' = case epsilon of
37 -- Compute f(a) and f(b) only if needed.
38 f_of_a' = case f_of_a of
42 f_of_b' = case f_of_b of
50 bisect :: (Fractional a, Ord a, Num b, Ord b)
51 => (a -> b) -- ^ The function @f@ whose root we seek
52 -> a -- ^ The \"left\" endpoint of the interval, @a@
53 -> a -- ^ The \"right\" endpoint of the interval, @b@
54 -> a -- ^ The tolerance, @epsilon@
55 -> Maybe b -- ^ Precomputed f(a)
56 -> Maybe b -- ^ Precomputed f(b)
58 bisect f a b epsilon f_of_a f_of_b
59 -- We pass @epsilon@ to the 'has_root' function because if we want a
60 -- result within epsilon of the true root, we need to know that
61 -- there *is* a root within an interval of length epsilon.
62 | not (has_root f a b (Just epsilon) (Just f_of_a') (Just f_of_b')) = Nothing
63 | f_of_a' == 0 = Just a
64 | f_of_b' == 0 = Just b
65 | (b - c) < epsilon = Just c
67 -- Use a 'prime' just for consistency.
69 if (has_root f a c (Just epsilon) (Just f_of_a') (Just f_of_c'))
70 then bisect f a c epsilon (Just f_of_a') (Just f_of_c')
71 else bisect f c b epsilon (Just f_of_c') (Just f_of_b')
73 -- Compute f(a) and f(b) only if needed.
74 f_of_a' = case f_of_a of
78 f_of_b' = case f_of_b of