pythonnumpymatrixfractionslinear-equation

How can i remove the denominator of all the Fractions


I used NumPy and Fractions module to find the answers to a given system of equations. But I want to convert all the answers to integers by dividing through by the highest denominator. How do I do that when I don't even know the values.

import numpy
from fractions import Fraction

a=[[3,4,1], 
   [2,3,0], 
   [4,3,-1]]
b=[[1], 
   [0], 
   [-2]]

values=numpy.linalg.solve(a, b)

for i in range(len(values)):
  num=values[i][0]  
  fractional_value=Fraction(num).limit_denominator()
  print(fractional_value)

Output:

-3/7 2/7 8/7

How do i remove the highest denominator assuming i dont know the output./


Solution

  • The minimal number that a set of numbers divides is called the least common multiple. Python unfortunately doesn't provide this function out of the box, but we can calculate it from gcd (which Python does provide) and the product.

    from math import gcd
    
    def lcm(a, b):
      if a == 0 and b == 0:
        return 0
      return a * b // gcd(a, b)
    

    Now we want to take a list of fractions and calculate the LCM of their denominators. I'll use a little tool called functools.reduce (which really should be in builtins, but that's beside the point)

    from functools import reduce
    
    frac_list = [Fraction(-3, 7), Fraction(2, 7), Fraction(8, 7)] # Example list
    denom_lcm = reduce(lcm, frac_list, 1)
    

    Then we can multiply all of the fractions by this denominator.

    whole_frac_list = [denom_lcm * x for x in frac_list]
    

    and, of course, if we want values of the int type, we can get that too

    whole_frac_list = [int(denom_lcm * x) for x in frac_list]