I have a list of floats which comes from some other function. What I know is that in ideal world there exist a common factor which can be used to multiply each term to obtain list of integers. There could be some small numerical noise (~1e-14).
So for example
[2.3333333333333335, 4.666666666666667, 1.0, 1.6666666666666667]
here each term can by multiplied by 3 to obtain
[7.0, 14.0, 3.0, 5.0]
How can I find this term? We can assume integer solution exists.
Any helpful comments will be appreciated
Python's Fraction type can convert floating points to rationals with denominators under 1000000, and then you can find the lowest common denominator.
>>> from fractions import Fraction
>>> a = [2.3333333333333335, 4.666666666666667, 1.0, 1.6666666666666667]
>>> [Fraction(x).limit_denominator() for x in a]
[Fraction(7, 3), Fraction(14, 3), Fraction(1, 1), Fraction(5, 3)]
A straightforward way to find the least common multiple using the math.gcd function:
>>> denoms = [3,3,1,2]
>>> functools.reduce(lambda a,b: a*b//math.gcd(a,b), denoms)
6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With