Debian Codegraph @

Doc/library/fractions.rst

raw
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
14 The :mod:`fractions` module provides support for rational number arithmetic.
15
16
17 A Fraction instance can be constructed from a pair of rational numbers, from
18 a single 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 a value equal to ``numerator/denominator``. If *denominator* is zero, 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 terms.
120 Guaranteed to be positive.
121
122
123 .. method:: as_integer_ratio()
124
125 Return a tuple of two integers, whose ratio is equal
126 to the original Fraction. The ratio is in lowest terms
127 and has a positive denominator.
128
129 .. versionadded:: 3.8
130
131 .. method:: is_integer()
132
133 Return ``True`` if the Fraction is an integer.
134
135 .. versionadded:: 3.12
136
137 .. classmethod:: from_float(f)
138
139 Alternative constructor which only accepts instances of
140 :class:`float` or :class:`numbers.Integral`. Beware that
141 ``Fraction.from_float(0.3)`` is not the same value as ``Fraction(3, 10)``.
142
143 .. note::
144
145 From Python 3.2 onwards, you can also construct a
146 :class:`Fraction` instance directly from a :class:`float`.
147
148
149 .. classmethod:: from_decimal(dec)
150
151 Alternative constructor which only accepts instances of
152 :class:`decimal.Decimal` or :class:`numbers.Integral`.
153
154 .. note::
155
156 From Python 3.2 onwards, you can also construct a
157 :class:`Fraction` instance directly from a :class:`decimal.Decimal`
158 instance.
159
160
161 .. method:: limit_denominator(max_denominator=1000000)
162
163 Finds and returns the closest :class:`Fraction` to ``self`` that has
164 denominator at most max_denominator. This method is useful for finding
165 rational approximations to a given floating-point number:
166
167 >>> from fractions import Fraction
168 >>> Fraction('3.1415926535897932').limit_denominator(1000)
169 Fraction(355, 113)
170
171 or for recovering a rational number that's represented as a float:
172
173 >>> from math import pi, cos
174 >>> Fraction(cos(pi/3))
175 Fraction(4503599627370497, 9007199254740992)
176 >>> Fraction(cos(pi/3)).limit_denominator()
177 Fraction(1, 2)
178 >>> Fraction(1.1).limit_denominator()
179 Fraction(11, 10)
180
181
182 .. method:: __floor__()
183
184 Returns the greatest :class:`int` ``<= self``. This method can
185 also be accessed through the :func:`math.floor` function:
186
187 >>> from math import floor
188 >>> floor(Fraction(355, 113))
189 3
190
191
192 .. method:: __ceil__()
193
194 Returns the least :class:`int` ``>= self``. This method can
195 also be accessed through the :func:`math.ceil` function.
196
197
198 .. method:: __round__()
199 __round__(ndigits)
200
201 The first version returns the nearest :class:`int` to ``self``,
202 rounding half to even. The second version rounds ``self`` to the
203 nearest multiple of ``Fraction(1, 10**ndigits)`` (logically, if
204 ``ndigits`` is negative), again rounding half toward even. This
205 method can also be accessed through the :func:`round` function.
206
207 .. method:: __format__(format_spec, /)
208
209 Provides support for formatting of :class:`Fraction` instances via the
210 :meth:`str.format` method, the :func:`format` built-in function, or
211 :ref:`Formatted string literals <f-strings>`.
212
213 If the ``format_spec`` format specification string does not end with one
214 of the presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``,
215 ``'G'`` or ``'%'`` then formatting follows the general rules for fill,
216 alignment, sign handling, minimum width, and grouping as described in the
217 :ref:`format specification mini-language <formatspec>`. The "alternate
218 form" flag ``'#'`` is supported: if present, it forces the output string
219 to always include an explicit denominator, even when the value being
220 formatted is an exact integer. The zero-fill flag ``'0'`` is not
221 supported.
222
223 If the ``format_spec`` format specification string ends with one of
224 the presentation types ``'e'``, ``'E'``, ``'f'``, ``'F'``, ``'g'``,
225 ``'G'`` or ``'%'`` then formatting follows the rules outlined for the
226 :class:`float` type in the :ref:`formatspec` section.
227
228 Here are some examples::
229
230 >>> from fractions import Fraction
231 >>> format(Fraction(103993, 33102), '_')
232 '103_993/33_102'
233 >>> format(Fraction(1, 7), '.^+10')
234 '...+1/7...'
235 >>> format(Fraction(3, 1), '')
236 '3'
237 >>> format(Fraction(3, 1), '#')
238 '3/1'
239 >>> format(Fraction(1, 7), '.40g')
240 '0.1428571428571428571428571428571428571429'
241 >>> format(Fraction('1234567.855'), '_.2f')
242 '1_234_567.86'
243 >>> f"{Fraction(355, 113):*>20.6e}"
244 '********3.141593e+00'
245 >>> old_price, new_price = 499, 672
246 >>> "{:.2%} price increase".format(Fraction(new_price, old_price) - 1)
247 '34.67% price increase'
248
249
250 .. seealso::
251
252 Module :mod:`numbers`
253 The abstract base classes making up the numeric tower.