Skip to content

Commit

Permalink
Add missing function
Browse files Browse the repository at this point in the history
  • Loading branch information
augustss committed Sep 26, 2024
1 parent 6007c49 commit 1ed82e6
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions lib/Data/Ratio.hs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module Data.Ratio(
Ratio, Rational,
(%),
numerator, denominator,
approxRational,
rationalInfinity,
rationalNaN,
rationalMinusZero,
Expand Down Expand Up @@ -112,3 +113,30 @@ instance (Ord a, Integral a) => RealFrac (Ratio a) where
(EQ, False) -> n
(EQ, True) -> n + x
(GT, _) -> n + x

approxRational :: (RealFrac a) => a -> a -> Rational
approxRational rat eps =
simplest (toRational rat - toRational eps) (toRational rat + toRational eps)
where
simplest x y
| y < x = simplest y x
| x == y = xr
| x > 0 = simplest' n d n' d'
| y < 0 = - simplest' (-n') d' (-n) d
| otherwise = 0 :% 1
where xr = toRational x
n = numerator xr
d = denominator xr
nd' = toRational y
n' = numerator nd'
d' = denominator nd'

simplest' n d n' d' -- assumes 0 < n%d < n'%d'
| r == 0 = q :% 1
| q /= q' = (q+1) :% 1
| otherwise = (q*n''+d'') :% n''
where (q,r) = quotRem n d
(q',r') = quotRem n' d'
nd'' = simplest' d' r' d r
n'' = numerator nd''
d'' = denominator nd''

0 comments on commit 1ed82e6

Please sign in to comment.