Skip to content

Instantly share code, notes, and snippets.

@kitayuta
Created January 22, 2011 16:42
Show Gist options
  • Save kitayuta/791231 to your computer and use it in GitHub Desktop.
Save kitayuta/791231 to your computer and use it in GitHub Desktop.
8行目をコメント解除するとコンパイル通らない
main = print $ binsearch (\x -> x^2 - 2) (0,10) 1e-20
binsearch :: Fractional a => Ord a => (a -> a) -> (a,a) -> a -> Maybe a
binsearch f (from,to) eps =
if (f from)*(f to) > 0 then Nothing
else Just $ binsearch' (from,to) from
where
-- binsearch' :: (a,a) -> a -> a
binsearch' (from',to') bef =
let mid = (from'+to') / fromRational 2
in if abs (bef-mid) <= eps then mid
else if f mid < fromRational 0 then binsearch' (mid,to') mid
else binsearch' (from',mid) mid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment