Skip to content

gh-91851: Trivial optimizations in Fraction #100791

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 3 commits into from
Jan 6, 2023
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
11 changes: 6 additions & 5 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,23 +650,24 @@ def __trunc__(a):

def __floor__(a):
"""math.floor(a)"""
return a.numerator // a.denominator
return a._numerator // a._denominator

def __ceil__(a):
"""math.ceil(a)"""
# The negations cleverly convince floordiv to return the ceiling.
return -(-a.numerator // a.denominator)
return -(-a._numerator // a._denominator)

def __round__(self, ndigits=None):
"""round(self, ndigits)

Rounds half toward even.
"""
if ndigits is None:
floor, remainder = divmod(self.numerator, self.denominator)
if remainder * 2 < self.denominator:
d = self._denominator
floor, remainder = divmod(self._numerator, d)
if remainder * 2 < d:
return floor
elif remainder * 2 > self.denominator:
elif remainder * 2 > d:
return floor + 1
# Deal with the half case:
elif floor % 2 == 0:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Microoptimizations for :meth:`fractions.Fraction.__round__`,
:meth:`fractions.Fraction.__ceil__` and
:meth:`fractions.Fraction.__floor__`.