Skip to content

Commit 5ba1cb0

Browse files
bpo-37819: Add Fraction.as_integer_ratio() (GH-15212) (GH-15215)
(cherry picked from commit f03b4c8) Co-authored-by: Raymond Hettinger <[email protected]>
1 parent 9500bbe commit 5ba1cb0

File tree

4 files changed

+23
-0
lines changed

4 files changed

+23
-0
lines changed

Doc/library/fractions.rst

+7
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,13 @@ another rational number, or from a string.
9494
Denominator of the Fraction in lowest term.
9595

9696

97+
.. method:: as_integer_ratio()
98+
99+
Return a tuple of two integers, whose ratio is equal
100+
to the Fraction and with a positive denominator.
101+
102+
.. versionadded:: 3.8
103+
97104
.. method:: from_float(flt)
98105

99106
This class method constructs a :class:`Fraction` representing the exact

Lib/fractions.py

+8
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,14 @@ def from_decimal(cls, dec):
216216
(cls.__name__, dec, type(dec).__name__))
217217
return cls(*dec.as_integer_ratio())
218218

219+
def as_integer_ratio(self):
220+
"""Return the integer ratio as a tuple.
221+
222+
Return a tuple of two integers, whose ratio is equal to the
223+
Fraction and with a positive denominator.
224+
"""
225+
return (self._numerator, self._denominator)
226+
219227
def limit_denominator(self, max_denominator=1000000):
220228
"""Closest Fraction to self with denominator at most max_denominator.
221229

Lib/test/test_fractions.py

+6
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,12 @@ def testFromDecimal(self):
302302
ValueError, "cannot convert NaN to integer ratio",
303303
F.from_decimal, Decimal("snan"))
304304

305+
def test_as_integer_ratio(self):
306+
self.assertEqual(F(4, 6).as_integer_ratio(), (2, 3))
307+
self.assertEqual(F(-4, 6).as_integer_ratio(), (-2, 3))
308+
self.assertEqual(F(4, -6).as_integer_ratio(), (-2, 3))
309+
self.assertEqual(F(0, 6).as_integer_ratio(), (0, 1))
310+
305311
def testLimitDenominator(self):
306312
rpi = F('3.1415926535897932')
307313
self.assertEqual(rpi.limit_denominator(10000), F(355, 113))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add Fraction.as_integer_ratio() to match the corresponding methods in bool,
2+
int, float, and decimal.

0 commit comments

Comments
 (0)