Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[3.8] bpo-37819: Add Fraction.as_integer_ratio() (GH-15212) #15215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Doc/library/fractions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,13 @@ another rational number, or from a string.
Denominator of the Fraction in lowest term.


.. method:: as_integer_ratio()

Return a tuple of two integers, whose ratio is equal
to the Fraction and with a positive denominator.

.. versionadded:: 3.8

.. method:: from_float(flt)

This class method constructs a :class:`Fraction` representing the exact
Expand Down
8 changes: 8 additions & 0 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,14 @@ def from_decimal(cls, dec):
(cls.__name__, dec, type(dec).__name__))
return cls(*dec.as_integer_ratio())

def as_integer_ratio(self):
"""Return the integer ratio as a tuple.

Return a tuple of two integers, whose ratio is equal to the
Fraction and with a positive denominator.
"""
return (self._numerator, self._denominator)

def limit_denominator(self, max_denominator=1000000):
"""Closest Fraction to self with denominator at most max_denominator.

Expand Down
6 changes: 6 additions & 0 deletions Lib/test/test_fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,12 @@ def testFromDecimal(self):
ValueError, "cannot convert NaN to integer ratio",
F.from_decimal, Decimal("snan"))

def test_as_integer_ratio(self):
self.assertEqual(F(4, 6).as_integer_ratio(), (2, 3))
self.assertEqual(F(-4, 6).as_integer_ratio(), (-2, 3))
self.assertEqual(F(4, -6).as_integer_ratio(), (-2, 3))
self.assertEqual(F(0, 6).as_integer_ratio(), (0, 1))

def testLimitDenominator(self):
rpi = F('3.1415926535897932')
self.assertEqual(rpi.limit_denominator(10000), F(355, 113))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add Fraction.as_integer_ratio() to match the corresponding methods in bool,
int, float, and decimal.