2 :mod:`fractions` --- Rational numbers
3 =====================================
6 :synopsis: Rational numbers.
7 .. moduleauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
8 .. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
12 The :mod:`fractions` module defines an immutable, infinite-precision
13 Fraction number class.
16 .. class:: Fraction(numerator=0, denominator=1)
17 Fraction(other_fraction)
20 The first version requires that *numerator* and *denominator* are
21 instances of :class:`numbers.Integral` and returns a new
22 ``Fraction`` representing ``numerator/denominator``. If
23 *denominator* is :const:`0`, raises a :exc:`ZeroDivisionError`. The
24 second version requires that *other_fraction* is an instance of
25 :class:`numbers.Rational` and returns an instance of
26 :class:`Fraction` with the same value. The third version expects a
27 string of the form ``[-+]?[0-9]+(/[0-9]+)?``, optionally surrounded
30 Implements all of the methods and operations from
31 :class:`numbers.Rational` and is immutable and hashable.
34 .. method:: Fraction.from_float(flt)
36 This classmethod constructs a :class:`Fraction` representing the
37 exact value of *flt*, which must be a :class:`float`. Beware that
38 ``Fraction.from_float(0.3)`` is not the same value as ``Fraction(3,
42 .. method:: Fraction.from_decimal(dec)
44 This classmethod constructs a :class:`Fraction` representing the
45 exact value of *dec*, which must be a
46 :class:`decimal.Decimal`.
49 .. method:: Fraction.limit_denominator(max_denominator=1000000)
51 Finds and returns the closest :class:`Fraction` to ``self`` that
52 has denominator at most max_denominator. This method is useful for
53 finding rational approximations to a given floating-point number::
55 >>> Fraction('3.1415926535897932').limit_denominator(1000)
58 or for recovering a rational number that's represented as a float::
60 >>> from math import pi, cos
61 >>> Fraction.from_float(cos(pi/3))
62 Fraction(4503599627370497L, 9007199254740992L)
63 >>> Fraction.from_float(cos(pi/3)).limit_denominator()
67 .. method:: Fraction.__floor__()
69 Returns the greatest :class:`int` ``<= self``. Will be accessible
70 through :func:`math.floor` in Py3k.
73 .. method:: Fraction.__ceil__()
75 Returns the least :class:`int` ``>= self``. Will be accessible
76 through :func:`math.ceil` in Py3k.
79 .. method:: Fraction.__round__()
80 Fraction.__round__(ndigits)
82 The first version returns the nearest :class:`int` to ``self``,
83 rounding half to even. The second version rounds ``self`` to the
84 nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if
85 ``ndigits`` is negative), again rounding half toward even. Will be
86 accessible through :func:`round` in Py3k.
92 The abstract base classes making up the numeric tower.