Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python How to Stop Automatic Reduction of Fractions

I was wondering if there is any way I can stop Python doing automatic reduction of fractions when using the fractions module. For example:

>>> import fractions
>>> fractions.Fraction(8,16)
Fraction(1, 2)

I would like to preserve the fraction as Fraction(8,16). Is that possible using a custom class or similar? Any sample code will be much appreciated!

Thank you! Sumant

like image 435
Sumant Murugesh Avatar asked Mar 20 '26 17:03

Sumant Murugesh


1 Answers

h/t "bowlofred" at python-forum.io for this undocumented hack:

from fractions import Fraction

def add_nonormal(a: Fraction, b: Fraction) -> Fraction:
    if a.denominator == b.denominator:
        c_numerator = a.numerator + b.numerator
        c_denominator = a.denominator
    else:
        c_numerator = a.numerator*b.denominator + b.numerator*a.denominator
        c_denominator = a.denominator*b.denominator
    return Fraction(c_numerator, c_denominator, _normalize=False)

def sub_nonormal(a: Fraction, b: Fraction) -> Fraction:
    return add_nonormal(a, -b)

def mul_nonormal(a: Fraction, b: Fraction) -> Fraction:
    c_numerator = a.numerator*b.numerator
    c_denominator = a.denominator*b.denominator
    return Fraction(c_numerator, c_denominator, _normalize=False)

def reciprocal_nonormal(x: Fraction) -> Fraction:
    return Fraction(*reversed(x.as_integer_ratio()), _normalize=False)

def div_nonormal(a: Fraction, b: Fraction) -> Fraction:
    return mul_nonormal(a, reciprocal_nonormal(b))

assert add_nonormal(Fraction(1, 6), Fraction(2, 6)).as_integer_ratio() == (3, 6)
assert add_nonormal(Fraction(1, 2), Fraction(1, 6)).as_integer_ratio() == (8, 12)

This is also useful if you're "mis"-using Fraction for extensive math, and all the unnecessary intermediate gcd calls start to bog down operation.

like image 73
JamesTheAwesomeDude Avatar answered Mar 23 '26 07:03

JamesTheAwesomeDude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!