David
David

Reputation: 69

How to simplify a fraction in Python?

still learning Python so any help is welcome. I have written a funtion to get a fraction, but more often than not the fraction can be simplified. My code does not do this yet. Any ideas how to simplify the fraction without using any import functions? code:

def add_frac(n1, d1, n2, d2):
    frac = (((n1 * d1) + (n2 * d2)), (d1 * d2))
    return frac

example: add_frac(1, 2, 1, 4) gives (6, 8) in stead of (3, 4)

Any help is welcome!

Upvotes: 2

Views: 5425

Answers (5)

Edouard Thiel
Edouard Thiel

Reputation: 6228

Here is a solution with a recursive implementation of gcd, using Euclid Algorithm; it also works on negative numbers :

def mygcd(a, b) :
    return gcd_rec(abs(a), abs(b))

def gcd_rec(a,b) :
    if a*b == 0 : return a+b
    if a <= b : return gcd_rec(a, b % a)
    return gcd_rec(a % b, b)

def add_frac(n1, d1, n2, d2):
    n = n1*d2 + n2*d1
    d = d1*d2
    g = mygcd(n, d)
    return n//g, d//g

Upvotes: 1

chepner
chepner

Reputation: 531165

The naive form of adding two fractions returns a correct answer, just not the most reduced correct answer. For that, you need to divide the numerator and denominator of the result by the greatest common denominator (GCD) of the original denominators. In this case, the GCD of 2 and 4 is 2, so dividing 6 and 8 by 2 gives the desired answer (3,4)

math.gcd can be used:

from math import gcd


def add_frac(n1, d1, n2, d2):
    x = gcd(d1, d2)
    frac = (((n1 * d2) + (n2 * d1)) / x, (d1 * d2) / x)
    return frac

though it sounds like you are expected to define your own implementation of gcd.

Upvotes: 1

QuadU
QuadU

Reputation: 321

In addition to above answers, if you cannot import any other libraries, here's is the implementation of fractions.gcd for python 2.7 (copied from https://stackoverflow.com/a/11175154/10155740)

>>> print inspect.getsource(gcd)
def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

so if you'd incorporate this in your code, you should get something like:

def gcd(a, b):
    while b:
        a, b = b, a%b
    return a

def add_frac(n1, d1, n2, d2):
    frac = (((n1 * d1) + (n2 * d2)), (d1 * d2))
    return tuple(i//gcd(*frac) for i in frac)

print(add_frac(1,2,1,4))
# OUTPUT: (3, 4)

Upvotes: 1

JunkyByte
JunkyByte

Reputation: 106

A pretty naive approach to get you started, you can add some checks to make it more efficient.

def simplify_frac(n, d):
    i = 2
    while i < min(n, d) + 1:
        if n % i == 0 and d % i == 0:
            n = n // i
            d = d // i
        else:
            i += 1
    return n, d

# Some examples 
In [105]: simplify_frac(2, 4)
Out[105]: (1, 2)

In [106]: simplify_frac(16, 36)
Out[106]: (4, 9)

In [107]: simplify_frac(7, 3)
Out[107]: (7, 3)

In [108]: simplify_frac(10, 1)
Out[108]: (10, 1)

In [109]: simplify_frac(1, 10)
Out[109]: (1, 10)

In [110]: simplify_frac(102, 10)
Out[110]: (51, 5)

In [111]: simplify_frac(110, 10)
Out[111]: (11, 1)

We use a modulo operator % to check the remainder from integer division by i, if both n and d have a remainder of 0 we know i divides them.

Upvotes: 2

Equinox
Equinox

Reputation: 6748

You need to divide it by GCD.

import math
def add_frac(n1, d1, n2, d2):
    nume = (n1 * d1) + (n2 * d2)
    deno = d1 * d2
    gcd = math.gcd(nume,deno)
    nume /= gcd
    deno /= gcd
    return (nume,deno)

>>> add_frac(1,2,1,4)
>>> (3.0, 4.0)

Upvotes: 0

Related Questions