3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow 2001
7 -- License : BSD-style (see the file libraries/base/LICENSE)
9 -- Maintainer : libraries@haskell.org
11 -- Portability : portable
13 -- Standard functions on rational numbers
15 -----------------------------------------------------------------------------
20 , (%) -- :: (Integral a) => a -> a -> Ratio a
21 , numerator -- :: (Integral a) => Ratio a -> a
22 , denominator -- :: (Integral a) => Ratio a -> a
23 , approxRational -- :: (RealFrac a) => a -> a -> Rational
26 -- (Integral a) => Eq (Ratio a)
27 -- (Integral a) => Ord (Ratio a)
28 -- (Integral a) => Num (Ratio a)
29 -- (Integral a) => Real (Ratio a)
30 -- (Integral a) => Fractional (Ratio a)
31 -- (Integral a) => RealFrac (Ratio a)
32 -- (Integral a) => Enum (Ratio a)
33 -- (Read a, Integral a) => Read (Ratio a)
34 -- (Integral a) => Show (Ratio a)
40 #ifdef __GLASGOW_HASKELL__
41 import GHC.Real -- The basic defns for Ratio
45 import Hugs.Prelude(Ratio(..), (%), numerator, denominator)
49 import Ratio (Ratio(..), (%), numerator, denominator, approxRational)
52 -- -----------------------------------------------------------------------------
55 -- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@,
56 -- returns the simplest rational number within @epsilon@ of @x@.
57 -- A rational number @y@ is said to be /simpler/ than another @y'@ if
59 -- * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and
61 -- * @'denominator' y <= 'denominator' y'@.
63 -- Any real interval contains a unique simplest rational;
64 -- in particular, note that @0\/1@ is the simplest rational of all.
66 -- Implementation details: Here, for simplicity, we assume a closed rational
67 -- interval. If such an interval includes at least one whole number, then
68 -- the simplest rational is the absolutely least whole number. Otherwise,
69 -- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d
70 -- and abs r' < d', and the simplest rational is q%1 + the reciprocal of
71 -- the simplest rational between d'%r' and d%r.
73 approxRational :: (RealFrac a) => a -> a -> Rational
74 approxRational rat eps = simplest (rat-eps) (rat+eps)
75 where simplest x y | y < x = simplest y x
77 | x > 0 = simplest' n d n' d'
78 | y < 0 = - simplest' (-n') d' (-n) d
80 where xr = toRational x
87 simplest' n d n' d' -- assumes 0 < n%d < n'%d'
89 | q /= q' = (q+1) :% 1
90 | otherwise = (q*n''+d'') :% n''
91 where (q,r) = quotRem n d
92 (q',r') = quotRem n' d'
93 nd'' = simplest' d' r' d r
95 d'' = denominator nd''