Question

Is there a simple way to simplify a ratio down? For example 1875:5625:625 would become 3:9:1.

I am using Python, but I'd like to know why and not just how.

Was it helpful?

Solution

Edit: Please note that fractions.gcd has been Deprecated since Python 3.5: Use math.gcd() instead.

There's a built-in gcd function in the fractions module so utilizing it I was able to get decent output:

from fractions import gcd

ratio = '1875:5625:625'

def solve(ratio):
    numbers = [int(i) for i in ratio.split(':')]
    denominater = reduce(gcd,numbers)
    solved = [i/denominater for i in numbers]
    return ':'.join(str(i) for i in solved)

ratio_2_solve =  solve(ratio)
print ratio_2_solve
#3:9:1

So given the ratio

1875:5625:625 

It would produce :

3:9:1

But that's not the best part of it, you could even put ratios like:

'1875:5625:625:5000:46875:46250'

And still get the output of:

3:9:1:8:75:74

OTHER TIPS

The way to simplify a ratio mathematically is to find the greatest common divisor (GCD) of all its factors, and let each of the factors divided by that GCD value. Here's an example:

1875 = 625 * 3
5625 = 625 * 9
625 = 625 * 1

so GCD(1875, 5625, 625) = 625
and 1875:5625:625 can be simplified to 3:9:1

So you could start writing some code. A common method for calculating GCD is the Euclidean Algorithm.

If you still have difficulties or other problems, please let me know.

Works in both Python 2 and 3.

def simplify(ratio_nums): return list(map(functools.reduce(fractions.gcd, ratio_nms).__rfloordiv__, ratio_nums))

Simplifying a ratio is essentially the same as simplifying the numbers in the ratio. To simplify a list of numbers the GCD (greatest common divisor) must be found and all the numbers must be divided by it.

fractions.gcd() computes the GCD of two numbers. To find the GCD of multiple numbers the first two numbers can be replaced with the GCD of themselves and the process repeated until one number is found. (GCD(GCD(n1, n2), n3)). For that one can use functools.reduce(), which runs the function passed as an argument (in this case fractions.gcd()) in such a manner. To divide all the numbers by the GCD one can map (which returns the return values of function, the first argument, called with the elements of the iterables which are the later arguments) the __rfloordiv__ special method of the GCD (which divides the argument by itself)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top