1 -----------------------------------------------------------------------------
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
9 -- Portability : portable
11 -- Standard functions on rational numbers
13 -----------------------------------------------------------------------------
18 , (%) -- :: (Integral a) => a -> a -> Ratio a
19 , numerator -- :: (Integral a) => Ratio a -> a
20 , denominator -- :: (Integral a) => Ratio a -> a
21 , approxRational -- :: (RealFrac a) => a -> a -> Rational
24 -- (Integral a) => Eq (Ratio a)
25 -- (Integral a) => Ord (Ratio a)
26 -- (Integral a) => Num (Ratio a)
27 -- (Integral a) => Real (Ratio a)
28 -- (Integral a) => Fractional (Ratio a)
29 -- (Integral a) => RealFrac (Ratio a)
30 -- (Integral a) => Enum (Ratio a)
31 -- (Read a, Integral a) => Read (Ratio a)
32 -- (Integral a) => Show (Ratio a)
38 #ifdef __GLASGOW_HASKELL__
39 import GHC.Real -- The basic defns for Ratio
43 import Hugs.Prelude(Ratio(..), (%), numerator, denominator)
47 import Ratio (Ratio(..), (%), numerator, denominator, approxRational)
50 -- -----------------------------------------------------------------------------
53 -- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@,
54 -- returns the simplest rational number within @epsilon@ of @x@.
55 -- A rational number @y@ is said to be simpler than another @y'@ if
57 -- * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and
59 -- * @'denominator' y <= 'denominator' y'@.
61 -- Any real interval contains a unique simplest rational.
63 -- Implementation details: Here, for simplicity, we assume a closed rational
64 -- interval. If such an interval includes at least one whole number, then
65 -- the simplest rational is the absolutely least whole number. Otherwise,
66 -- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d
67 -- and abs r' < d', and the simplest rational is q%1 + the reciprocal of
68 -- the simplest rational between d'%r' and d%r.
70 approxRational :: (RealFrac a) => a -> a -> Rational
71 approxRational rat eps = simplest (rat-eps) (rat+eps)
72 where simplest x y | y < x = simplest y x
74 | x > 0 = simplest' n d n' d'
75 | y < 0 = - simplest' (-n') d' (-n) d
77 where xr = toRational x
84 simplest' n d n' d' -- assumes 0 < n%d < n'%d'
86 | q /= q' = (q+1) :% 1
87 | otherwise = (q*n''+d'') :% n''
88 where (q,r) = quotRem n d
89 (q',r') = quotRem n' d'
90 nd'' = simplest' d' r' d r
92 d'' = denominator nd''