blob: 8ed702f5f8c924f48b3f116afe0f3798c6456464 [file] [log] [blame]
Jeffrey Yasskind7b00332008-01-15 07:46:24 +00001
2:mod:`rational` --- Rational numbers
3====================================
4
5.. module:: rational
6 :synopsis: Rational numbers.
7.. moduleauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
8.. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
9.. versionadded:: 2.6
10
11
12The :mod:`rational` module defines an immutable, infinite-precision
13Rational number class.
14
15
16.. class:: Rational(numerator=0, denominator=1)
17 Rational(other_rational)
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000018 Rational(string)
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000019
20 The first version requires that *numerator* and *denominator* are
21 instances of :class:`numbers.Integral` and returns a new
22 ``Rational`` representing ``numerator/denominator``. If
23 *denominator* is :const:`0`, raises a :exc:`ZeroDivisionError`. The
24 second version requires that *other_rational* is an instance of
25 :class:`numbers.Rational` and returns an instance of
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000026 :class:`Rational` with the same value. The third version expects a
27 string of the form ``[-+]?[0-9]+(/[0-9]+)?``, optionally surrounded
28 by spaces.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000029
30 Implements all of the methods and operations from
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000031 :class:`numbers.Rational` and is immutable and hashable.
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000032
33
34.. method:: Rational.from_float(flt)
35
36 This classmethod constructs a :class:`Rational` representing the
37 exact value of *flt*, which must be a :class:`float`. Beware that
38 ``Rational.from_float(0.3)`` is not the same value as ``Rational(3,
39 10)``
40
41
Jeffrey Yasskin45169fb2008-01-19 09:56:06 +000042.. method:: Rational.from_decimal(dec)
43
44 This classmethod constructs a :class:`Rational` representing the
45 exact value of *dec*, which must be a
46 :class:`decimal.Decimal`.
47
48
Jeffrey Yasskind7b00332008-01-15 07:46:24 +000049.. method:: Rational.__floor__()
50
51 Returns the greatest :class:`int` ``<= self``. Will be accessible
52 through :func:`math.floor` in Py3k.
53
54
55.. method:: Rational.__ceil__()
56
57 Returns the least :class:`int` ``>= self``. Will be accessible
58 through :func:`math.ceil` in Py3k.
59
60
61.. method:: Rational.__round__()
62 Rational.__round__(ndigits)
63
64 The first version returns the nearest :class:`int` to ``self``,
65 rounding half to even. The second version rounds ``self`` to the
66 nearest multiple of ``Rational(1, 10**ndigits)`` (logically, if
67 ``ndigits`` is negative), again rounding half toward even. Will be
68 accessible through :func:`round` in Py3k.
69
70
71.. seealso::
72
73 Module :mod:`numbers`
74 The abstract base classes making up the numeric tower.
75