mirror of
https://github.com/python/cpython.git
synced 2025-10-08 08:01:55 +00:00
gh-91851: Trivial optimizations in Fraction (#100791)
Make some trivial performance optimizations in Fraction Uses private class attributes `_numerator` and `_denominator` in place of the `numerator` and `denominator` property accesses. Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
This commit is contained in:
parent
15c44789bb
commit
0e640260da
2 changed files with 9 additions and 5 deletions
|
@ -650,12 +650,12 @@ class Fraction(numbers.Rational):
|
||||||
|
|
||||||
def __floor__(a):
|
def __floor__(a):
|
||||||
"""math.floor(a)"""
|
"""math.floor(a)"""
|
||||||
return a.numerator // a.denominator
|
return a._numerator // a._denominator
|
||||||
|
|
||||||
def __ceil__(a):
|
def __ceil__(a):
|
||||||
"""math.ceil(a)"""
|
"""math.ceil(a)"""
|
||||||
# The negations cleverly convince floordiv to return the ceiling.
|
# The negations cleverly convince floordiv to return the ceiling.
|
||||||
return -(-a.numerator // a.denominator)
|
return -(-a._numerator // a._denominator)
|
||||||
|
|
||||||
def __round__(self, ndigits=None):
|
def __round__(self, ndigits=None):
|
||||||
"""round(self, ndigits)
|
"""round(self, ndigits)
|
||||||
|
@ -663,10 +663,11 @@ class Fraction(numbers.Rational):
|
||||||
Rounds half toward even.
|
Rounds half toward even.
|
||||||
"""
|
"""
|
||||||
if ndigits is None:
|
if ndigits is None:
|
||||||
floor, remainder = divmod(self.numerator, self.denominator)
|
d = self._denominator
|
||||||
if remainder * 2 < self.denominator:
|
floor, remainder = divmod(self._numerator, d)
|
||||||
|
if remainder * 2 < d:
|
||||||
return floor
|
return floor
|
||||||
elif remainder * 2 > self.denominator:
|
elif remainder * 2 > d:
|
||||||
return floor + 1
|
return floor + 1
|
||||||
# Deal with the half case:
|
# Deal with the half case:
|
||||||
elif floor % 2 == 0:
|
elif floor % 2 == 0:
|
||||||
|
|
|
@ -0,0 +1,3 @@
|
||||||
|
Microoptimizations for :meth:`fractions.Fraction.__round__`,
|
||||||
|
:meth:`fractions.Fraction.__ceil__` and
|
||||||
|
:meth:`fractions.Fraction.__floor__`.
|
Loading…
Add table
Add a link
Reference in a new issue