3 November 2020

BigFraction

When you add fractions a bunch of times, the numerator and denominator have a large propensity to keep getting bigger. This means that we need to have extended-precision integer arithmetic if we are going to create a class for fractions.

Python has extended-precision integer arithmetic in its regular integer type. Java does not; it has an object type java.math.BigInteger. In both cases, the state of a fraction is specfied by its numerator and denominator.


def gcd(a,b):
    if a < 0:
        a = -a
    if b < 0:
        b = -b
    if a == 0:
        return b
    if b == 0:
        return a
    while b%a > 0:
        r = b%a
        b, a = a,  b%a
    return a
class BigFraction(object):
    def __init__(self, num, denom):
        if denom == 0:
            raise ValueError
        if denom < 0:
            num = -num
            denom = -denom
        d = gcd(num, denom)
        num //= d
        denom //= d
        self.num = num
        self.denom = denom
    def __str__(self):
        return f"{self.num}/{self.denom}"
    def __eq__(self, other):
        return self.num == other.num and self.denom == other.denom

def main():
    f = BigFraction(2,4)
    print(f.denom)
    print(f.num)
    g = BigFraction(1,2)
    h = BigFraction(1,-2)
    print(f, g, h)
    print(f == g)
main()