1 {-# LANGUAGE Safe #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module : Data.Ratio
6 -- Copyright : (c) The University of Glasgow 2001
8 --
10 -- Stability : stable
11 -- Portability : portable
12 --
13 -- Standard functions on rational numbers
14 --
15 -----------------------------------------------------------------------------
17 module Data.Ratio
18 ( Ratio
19 , Rational
20 , (%)
21 , numerator
22 , denominator
23 , approxRational
25 ) where
27 import Prelude
29 import GHC.Real -- The basic defns for Ratio
31 -- -----------------------------------------------------------------------------
32 -- approxRational
34 -- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@,
35 -- returns the simplest rational number within @epsilon@ of @x@.
36 -- A rational number @y@ is said to be /simpler/ than another @y'@ if
37 --
38 -- * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and
39 --
40 -- * @'denominator' y <= 'denominator' y'@.
41 --
42 -- Any real interval contains a unique simplest rational;
43 -- in particular, note that @0\/1@ is the simplest rational of all.
45 -- Implementation details: Here, for simplicity, we assume a closed rational
46 -- interval. If such an interval includes at least one whole number, then
47 -- the simplest rational is the absolutely least whole number. Otherwise,
48 -- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d
49 -- and abs r' < d', and the simplest rational is q%1 + the reciprocal of
50 -- the simplest rational between d'%r' and d%r.
52 approxRational :: (RealFrac a) => a -> a -> Rational
53 approxRational rat eps = simplest (rat-eps) (rat+eps)
54 where simplest x y | y < x = simplest y x
55 | x == y = xr
56 | x > 0 = simplest' n d n' d'
57 | y < 0 = - simplest' (-n') d' (-n) d
58 | otherwise = 0 :% 1
59 where xr = toRational x
60 n = numerator xr
61 d = denominator xr
62 nd' = toRational y
63 n' = numerator nd'
64 d' = denominator nd'
66 simplest' n d n' d' -- assumes 0 < n%d < n'%d'
67 | r == 0 = q :% 1
68 | q /= q' = (q+1) :% 1
69 | otherwise = (q*n''+d'') :% n''
70 where (q,r) = quotRem n d
71 (q',r') = quotRem n' d'
72 nd'' = simplest' d' r' d r
73 n'' = numerator nd''
74 d'' = denominator nd''