• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`!fractions` --- Rational numbers
2======================================
3
4.. module:: fractions
5   :synopsis: Rational numbers.
6
7.. moduleauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
8.. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
9
10**Source code:** :source:`Lib/fractions.py`
11
12--------------
13
14The :mod:`fractions` module provides support for rational number arithmetic.
15
16
17A Fraction instance can be constructed from a pair of integers, from
18another rational number, or from a string.
19
20.. class:: Fraction(numerator=0, denominator=1)
21           Fraction(other_fraction)
22           Fraction(float)
23           Fraction(decimal)
24           Fraction(string)
25
26   The first version requires that *numerator* and *denominator* are instances
27   of :class:`numbers.Rational` and returns a new :class:`Fraction` instance
28   with value ``numerator/denominator``. If *denominator* is ``0``, it
29   raises a :exc:`ZeroDivisionError`. The second version requires that
30   *other_fraction* is an instance of :class:`numbers.Rational` and returns a
31   :class:`Fraction` instance with the same value.  The next two versions accept
32   either a :class:`float` or a :class:`decimal.Decimal` instance, and return a
33   :class:`Fraction` instance with exactly the same value.  Note that due to the
34   usual issues with binary floating point (see :ref:`tut-fp-issues`), the
35   argument to ``Fraction(1.1)`` is not exactly equal to 11/10, and so
36   ``Fraction(1.1)`` does *not* return ``Fraction(11, 10)`` as one might expect.
37   (But see the documentation for the :meth:`limit_denominator` method below.)
38   The last version of the constructor expects a string or unicode instance.
39   The usual form for this instance is::
40
41      [sign] numerator ['/' denominator]
42
43   where the optional ``sign`` may be either '+' or '-' and
44   ``numerator`` and ``denominator`` (if present) are strings of
45   decimal digits (underscores may be used to delimit digits as with
46   integral literals in code).  In addition, any string that represents a finite
47   value and is accepted by the :class:`float` constructor is also
48   accepted by the :class:`Fraction` constructor.  In either form the
49   input string may also have leading and/or trailing whitespace.
50   Here are some examples::
51
52      >>> from fractions import Fraction
53      >>> Fraction(16, -10)
54      Fraction(-8, 5)
55      >>> Fraction(123)
56      Fraction(123, 1)
57      >>> Fraction()
58      Fraction(0, 1)
59      >>> Fraction('3/7')
60      Fraction(3, 7)
61      >>> Fraction(' -3/7 ')
62      Fraction(-3, 7)
63      >>> Fraction('1.414213 \t\n')
64      Fraction(1414213, 1000000)
65      >>> Fraction('-.125')
66      Fraction(-1, 8)
67      >>> Fraction('7e-6')
68      Fraction(7, 1000000)
69      >>> Fraction(2.25)
70      Fraction(9, 4)
71      >>> Fraction(1.1)
72      Fraction(2476979795053773, 2251799813685248)
73      >>> from decimal import Decimal
74      >>> Fraction(Decimal('1.1'))
75      Fraction(11, 10)
76
77
78   The :class:`Fraction` class inherits from the abstract base class
79   :class:`numbers.Rational`, and implements all of the methods and
80   operations from that class.  :class:`Fraction` instances are :term:`hashable`,
81   and should be treated as immutable.  In addition,
82   :class:`Fraction` has the following properties and methods:
83
84   .. versionchanged:: 3.2
85      The :class:`Fraction` constructor now accepts :class:`float` and
86      :class:`decimal.Decimal` instances.
87
88   .. versionchanged:: 3.9
89      The :func:`math.gcd` function is now used to normalize the *numerator*
90      and *denominator*. :func:`math.gcd` always returns an :class:`int` type.
91      Previously, the GCD type depended on *numerator* and *denominator*.
92
93   .. versionchanged:: 3.11
94      Underscores are now permitted when creating a :class:`Fraction` instance
95      from a string, following :PEP:`515` rules.
96
97   .. versionchanged:: 3.11
98      :class:`Fraction` implements ``__int__`` now to satisfy
99      ``typing.SupportsInt`` instance checks.
100
101   .. versionchanged:: 3.12
102      Space is allowed around the slash for string inputs: ``Fraction('2 / 3')``.
103
104   .. versionchanged:: 3.12
105      :class:`Fraction` instances now support float-style formatting, with
106      presentation types ``"e"``, ``"E"``, ``"f"``, ``"F"``, ``"g"``, ``"G"``
107      and ``"%""``.
108
109   .. versionchanged:: 3.13
110      Formatting of :class:`Fraction` instances without a presentation type
111      now supports fill, alignment, sign handling, minimum width and grouping.
112
113   .. attribute:: numerator
114
115      Numerator of the Fraction in lowest term.
116
117   .. attribute:: denominator
118
119      Denominator of the Fraction in lowest term.
120
121
122   .. method:: as_integer_ratio()
123
124      Return a tuple of two integers, whose ratio is equal
125      to the original Fraction.  The ratio is in lowest terms
126      and has a positive denominator.
127
128      .. versionadded:: 3.8
129
130   .. method:: is_integer()
131
132      Return ``True`` if the Fraction is an integer.
133
134      .. versionadded:: 3.12
135
136   .. classmethod:: from_float(flt)
137
138      Alternative constructor which only accepts instances of
139      :class:`float` or :class:`numbers.Integral`. Beware that
140      ``Fraction.from_float(0.3)`` is not the same value as ``Fraction(3, 10)``.
141
142      .. note::
143
144         From Python 3.2 onwards, you can also construct a
145         :class:`Fraction` instance directly from a :class:`float`.
146
147
148   .. classmethod:: from_decimal(dec)
149
150      Alternative constructor which only accepts instances of
151      :class:`decimal.Decimal` or :class:`numbers.Integral`.
152
153      .. note::
154
155         From Python 3.2 onwards, you can also construct a
156         :class:`Fraction` instance directly from a :class:`decimal.Decimal`
157         instance.
158
159
160   .. method:: limit_denominator(max_denominator=1000000)
161
162      Finds and returns the closest :class:`Fraction` to ``self`` that has
163      denominator at most max_denominator.  This method is useful for finding
164      rational approximations to a given floating-point number:
165
166         >>> from fractions import Fraction
167         >>> Fraction('3.1415926535897932').limit_denominator(1000)
168         Fraction(355, 113)
169
170      or for recovering a rational number that's represented as a float:
171
172         >>> from math import pi, cos
173         >>> Fraction(cos(pi/3))
174         Fraction(4503599627370497, 9007199254740992)
175         >>> Fraction(cos(pi/3)).limit_denominator()
176         Fraction(1, 2)
177         >>> Fraction(1.1).limit_denominator()
178         Fraction(11, 10)
179
180
181   .. method:: __floor__()
182
183      Returns the greatest :class:`int` ``<= self``.  This method can
184      also be accessed through the :func:`math.floor` function:
185
186        >>> from math import floor
187        >>> floor(Fraction(355, 113))
188        3
189
190
191   .. method:: __ceil__()
192
193      Returns the least :class:`int` ``>= self``.  This method can
194      also be accessed through the :func:`math.ceil` function.
195
196
197   .. method:: __round__()
198               __round__(ndigits)
199
200      The first version returns the nearest :class:`int` to ``self``,
201      rounding half to even. The second version rounds ``self`` to the
202      nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if
203      ``ndigits`` is negative), again rounding half toward even.  This
204      method can also be accessed through the :func:`round` function.
205
206   .. method:: __format__(format_spec, /)
207
208      Provides support for formatting of :class:`Fraction` instances via the
209      :meth:`str.format` method, the :func:`format` built-in function, or
210      :ref:`Formatted string literals <f-strings>`.
211
212      If the ``format_spec`` format specification string does not end with one
213      of the presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``,
214      ``'G'`` or ``'%'`` then formatting follows the general rules for fill,
215      alignment, sign handling, minimum width, and grouping as described in the
216      :ref:`format specification mini-language <formatspec>`. The "alternate
217      form" flag ``'#'`` is supported: if present, it forces the output string
218      to always include an explicit denominator, even when the value being
219      formatted is an exact integer. The zero-fill flag ``'0'`` is not
220      supported.
221
222      If the ``format_spec`` format specification string ends with one of
223      the presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``,
224      ``'G'`` or ``'%'`` then formatting follows the rules outlined for the
225      :class:`float` type in the :ref:`formatspec` section.
226
227      Here are some examples::
228
229         >>> from fractions import Fraction
230         >>> format(Fraction(103993, 33102), '_')
231         '103_993/33_102'
232         >>> format(Fraction(1, 7), '.^+10')
233         '...+1/7...'
234         >>> format(Fraction(3, 1), '')
235         '3'
236         >>> format(Fraction(3, 1), '#')
237         '3/1'
238         >>> format(Fraction(1, 7), '.40g')
239         '0.1428571428571428571428571428571428571429'
240         >>> format(Fraction('1234567.855'), '_.2f')
241         '1_234_567.86'
242         >>> f"{Fraction(355, 113):*>20.6e}"
243         '********3.141593e+00'
244         >>> old_price, new_price = 499, 672
245         >>> "{:.2%} price increase".format(Fraction(new_price, old_price) - 1)
246         '34.67% price increase'
247
248
249.. seealso::
250
251   Module :mod:`numbers`
252      The abstract base classes making up the numeric tower.
253