This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author rhettinger
Recipients Sergey.Kirpichev, rhettinger
Date 2021-03-06.17:20:02
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1615051203.41.0.531162510709.issue43420@roundup.psfhosted.org>
In-reply-to
Content
Here's some code to try out:

from math import gcd
from fractions import Fraction
import operator
import math

class Henrici(Fraction):
    'Reformulate _mul to reduce the size of intermediate products'

    # Original has 2 multiplications, 1 gcd calls, and 2 divisions
    # This one has 2 multiplications, 2 gcd calls, and 4 divisions  

    def _mul(a, b):
        a_n, a_d = a.numerator, a.denominator
        b_n, b_d = b.numerator, b.denominator
        d1 = math.gcd(a_n, b_d)
        a_n //= d1
        b_d //= d1
        d2 = math.gcd(b_n, a_d)
        b_n //= d2
        a_d //= d2
        result = Fraction(a_n * b_n, a_d * b_d, _normalize=False)
        assert math.gcd(a_n * b_n, a_d * b_d) == 1 and a_d * b_d >= 0
        return result

    __mul__, __rmul__ = Fraction._operator_fallbacks(_mul, operator.mul)

assert Henrici(10, 3) * Henrici(6, 5) == Henrici(4, 1)
History
Date User Action Args
2021-03-06 17:20:03rhettingersetrecipients: + rhettinger, Sergey.Kirpichev
2021-03-06 17:20:03rhettingersetmessageid: <1615051203.41.0.531162510709.issue43420@roundup.psfhosted.org>
2021-03-06 17:20:03rhettingerlinkissue43420 messages
2021-03-06 17:20:02rhettingercreate