+trisect :: (RealField.C a,
+ RealRing.C b,
+ Absolute.C b)
+ => (a -> b) -- ^ The function @f@ whose root we seek
+ -> a -- ^ The \"left\" endpoint of the interval, @a@
+ -> a -- ^ The \"right\" endpoint of the interval, @b@
+ -> a -- ^ The tolerance, @epsilon@
+ -> Maybe b -- ^ Precomputed f(a)
+ -> Maybe b -- ^ Precomputed f(b)
+ -> Maybe a
+trisect f a b epsilon f_of_a f_of_b
+ -- We pass @epsilon@ to the 'has_root' function because if we want a
+ -- result within epsilon of the true root, we need to know that
+ -- there *is* a root within an interval of length epsilon.
+ | not (has_root f a b (Just epsilon) (Just f_of_a') (Just f_of_b')) = Nothing
+ | f_of_a' == 0 = Just a
+ | f_of_b' == 0 = Just b
+ | otherwise =
+ -- Use a 'prime' just for consistency.
+ let (a', b', fa', fb')
+ | has_root f d b (Just epsilon) (Just f_of_d') (Just f_of_b') =
+ (d, b, f_of_d', f_of_b')
+ | has_root f c d (Just epsilon) (Just f_of_c') (Just f_of_d') =
+ (c, d, f_of_c', f_of_d')
+ | otherwise =
+ (a, c, f_of_a', f_of_c')
+ in
+ if (b-a) < 2*epsilon
+ then Just ((b+a)/2)
+ else trisect f a' b' epsilon (Just fa') (Just fb')
+ where
+ -- Compute f(a) and f(b) only if needed.
+ f_of_a' = fromMaybe (f a) f_of_a
+ f_of_b' = fromMaybe (f b) f_of_b
+
+ c = (2*a + b) / 3
+
+ d = (a + 2*b) / 3
+
+ f_of_c' = f c
+ f_of_d' = f d
+
+
+