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