I know I can use: - 0.5.as_integer_ratio() ; and get the integer fraction: 1/2
However, if I have a decimal such as: - 8.333333333333334 ; which is equivalent to: 25/3 ; and I use the 8.333333333333334.as_integer_ratio() ; I get: (4691061961859793, 562949953421312)
Is there a function/way to get to the "clean" 25/3 instead?
If you want exact representation of fractions like 25/3, you shouldn't be doing your math in floating point in the first place. You should use an exact rational type, like fractions.Fraction:
from fractions import Fraction
x = Fraction(75)
y = x/9
print(y)
Output:
25/3
If you're stuck with a floating-point number or a decimal string, you can convert it to a Fraction and use limit_denominator to find a nearby fraction with a small denominator. By default, "small" is treated as <= 1000000, but you can configure the limit.
print(Fraction(8.333333333333334).limit_denominator())
Output:
25/3
Handling everything in rational arithmetic from the start is almost always better, though.
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