]> gitweb.michael.orlitzky.com - numerical-analysis.git/blob - src/Roots/Fast.hs
Split Roots into Roots.Simple and Roots.Fast.
[numerical-analysis.git] / src / Roots / Fast.hs
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.
5
6 module Roots.Fast
7 where
8
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)
17 -> Bool
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!
21 True
22 else
23 if (b - a) <= epsilon' then
24 -- Give up, return false.
25 False
26 else
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'))
30 where
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
34 Nothing -> (b-a)
35 Just eps -> eps
36
37 -- Compute f(a) and f(b) only if needed.
38 f_of_a' = case f_of_a of
39 Nothing -> f a
40 Just v -> v
41
42 f_of_b' = case f_of_b of
43 Nothing -> f b
44 Just v -> v
45
46 c = (a + b)/2
47
48
49
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)
57 -> Maybe a
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
66 | otherwise =
67 -- Use a 'prime' just for consistency.
68 let f_of_c' = f c in
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')
72 where
73 -- Compute f(a) and f(b) only if needed.
74 f_of_a' = case f_of_a of
75 Nothing -> f a
76 Just v -> v
77
78 f_of_b' = case f_of_b of
79 Nothing -> f b
80 Just v -> v
81
82 c = (a + b) / 2