Skip to content

Instantly share code, notes, and snippets.

@PhDP
Last active December 18, 2015 21:48
Show Gist options
  • Save PhDP/5849881 to your computer and use it in GitHub Desktop.
Save PhDP/5849881 to your computer and use it in GitHub Desktop.
Safe bisection algorithm in Haskell.
bisection :: (Double -> Double) -> Double -> Double -> Double -> Maybe Double
bisection f a b err
| err < 1e-15 = Nothing
| abs (b - a) / 2 < err = Nothing
| a < b = bis a b
| otherwise = bis b a
where
bis a b
| d < err || f m == 0.0 = Just m
| f a * f m < 0.0 = bis a m
| f m * f b < 0.0 = bis m b
| otherwise = Nothing
where
d = (b - a) / 2
m = (b + a) / 2
@PhDP
Copy link
Author

PhDP commented Jun 24, 2013

I prefer to explicitly type it to ensure precision is high enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment