Because floating point values can be imprecise, you can end up with 'weird' fractions; limit the denominator to 'simplify' the fraction somewhat, with Fraction.limit_denominator():
To expand upon Martijn Pieters excellent answer with an additional option due to the imprecision inherent with more complex floats. For example:
>>> f = 0.8857097
>>> f.as_integer_ratio()
(1994440937439217, 2251799813685248) # mathematically wrong
>>> Fraction(f)
Fraction(1994440937439217, 2251799813685248) # same result but in a class
>>> Fraction(f).limit_denominator()
Fraction(871913, 984423) # still imprecise
The mathematical result desired was 8857097/10000000 which can be achieved by casting to a string and then manipulating it.
Edited Response
I found a much simpler way to resolve the accuracy issue.
>>> Fraction(str(f))
Fraction(8857097, 10000000)
Casting as to a string also allows for accurate Decimal instances
I will note that this kind of fraction precision is not optimized and will usually not be needed, but for completeness it is here. This function doesn't simplify the fraction, but you can do additional processing to reduce it:
from fractions import Fraction
decimals = [0.25, 0.5, 1.25, 3, 0.6, 0.84]
for d in decimals:
print(Fraction(str(d))) #Cast as string for proper fraction
By using Decimal:
from decimal import Decimal
decimals = [0.25, 0.5, 1.25, 3, 0.6, 0.84]
for d in decimals:
d = Decimal(str(d)) #Cast as string for proper fraction
nominator,denominator = d.as_integer_ratio()
if denominator==1:
print(a)
else:
print(nominator,denominator, sep="/")