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./
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.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 inbuiltins
, but that's beside the point)Then we can multiply all of the fractions by this denominator.
and, of course, if we want values of the
int
type, we can get that too