Skip to content

Commit 909982e

Browse files
authored
gh-91851: Micro optimizations for arithmetic between Fractions (#25518)
Adapted from 046c84e8f9 This makes arithmetic between Fractions with small components just as fast as before #24779, at some expense of mixed arithmetic (e.g. Fraction + int).
1 parent 6d3bc4a commit 909982e

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

Lib/fractions.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -395,8 +395,10 @@ class doesn't subclass a concrete type, there's no
395395
396396
"""
397397
def forward(a, b):
398-
if isinstance(b, (int, Fraction)):
398+
if isinstance(b, Fraction):
399399
return monomorphic_operator(a, b)
400+
elif isinstance(b, int):
401+
return monomorphic_operator(a, Fraction(b))
400402
elif isinstance(b, float):
401403
return fallback_operator(float(a), b)
402404
elif isinstance(b, complex):
@@ -409,7 +411,7 @@ def forward(a, b):
409411
def reverse(b, a):
410412
if isinstance(a, numbers.Rational):
411413
# Includes ints.
412-
return monomorphic_operator(a, b)
414+
return monomorphic_operator(Fraction(a), b)
413415
elif isinstance(a, numbers.Real):
414416
return fallback_operator(float(a), float(b))
415417
elif isinstance(a, numbers.Complex):
@@ -491,8 +493,8 @@ def reverse(b, a):
491493

492494
def _add(a, b):
493495
"""a + b"""
494-
na, da = a.numerator, a.denominator
495-
nb, db = b.numerator, b.denominator
496+
na, da = a._numerator, a._denominator
497+
nb, db = b._numerator, b._denominator
496498
g = math.gcd(da, db)
497499
if g == 1:
498500
return Fraction(na * db + da * nb, da * db, _normalize=False)
@@ -507,8 +509,8 @@ def _add(a, b):
507509

508510
def _sub(a, b):
509511
"""a - b"""
510-
na, da = a.numerator, a.denominator
511-
nb, db = b.numerator, b.denominator
512+
na, da = a._numerator, a._denominator
513+
nb, db = b._numerator, b._denominator
512514
g = math.gcd(da, db)
513515
if g == 1:
514516
return Fraction(na * db - da * nb, da * db, _normalize=False)
@@ -523,8 +525,8 @@ def _sub(a, b):
523525

524526
def _mul(a, b):
525527
"""a * b"""
526-
na, da = a.numerator, a.denominator
527-
nb, db = b.numerator, b.denominator
528+
na, da = a._numerator, a._denominator
529+
nb, db = b._numerator, b._denominator
528530
g1 = math.gcd(na, db)
529531
if g1 > 1:
530532
na //= g1
@@ -540,8 +542,8 @@ def _mul(a, b):
540542
def _div(a, b):
541543
"""a / b"""
542544
# Same as _mul(), with inversed b.
543-
na, da = a.numerator, a.denominator
544-
nb, db = b.numerator, b.denominator
545+
na, da = a._numerator, a._denominator
546+
nb, db = b._numerator, b._denominator
545547
g1 = math.gcd(na, nb)
546548
if g1 > 1:
547549
na //= g1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Optimize the :class:`~fractions.Fraction` arithmetics for small components.

0 commit comments

Comments
 (0)