David
David

Reputation: 69

Simplify fraction function does not work properly in Python

i've made an simplifying function and it works fine, but not perfect.

def gcd(a, b):

    while b > 0:
        if a == 0:
            return b
        a, b = b, (a % b)

def add_frac(n1, d1, n2, d2):

    g = gcd(d1, d2)
    
    frac = (((n1 * d2) + (n2 * d1)) // g, (d1 * d2) // g)
    return frac

when I try: print(add_frac(1, 2, 1, 6))it returns (4, 6). I want it to be (2, 3). Any help to get this result? Note! I would like to get the result without using import math

Example that works: print(add_frac(1, 2, 1, 4)) gives (3, 4)

Upvotes: 0

Views: 93

Answers (2)

Amazonian_panda
Amazonian_panda

Reputation: 64

One option would be to use the Fractions module in python

>>>print(Fraction(1, 2) + Fraction(1, 6))
>>>2/3

Or if you want to write you own python code, then change gcd method to

def gcd(a,b):
    if(b==0):
        return a
    else:
        return gcd(b,a%b)

and add_frac method to

def add_frac(n1, d1, n2, d2):

    g = gcd(d1, d2)
    frac = ((d1/g)*n1 + (d2/g)*n2, g)
    return frac

Note that since we already found the gcd we dont need floor division(//) as we know d1 and d2 will be divisible by g

Upvotes: 0

Ali Zaini
Ali Zaini

Reputation: 88

Using your methodology, just find the GCD of the resulting numerator and denominator and divide by that

def add_frac(n1, d1, n2, d2):
    num = (n1*d2 + n2*d1)
    den = d1*d2
    g = gcd(num,den)
    return num/g, den/g

Upvotes: 2

Related Questions