Skip to content Skip to sidebar Skip to footer

Is There An Alternative To The: As_integer_ratio(), For Getting "cleaner" Fractions?

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

Solution 1:

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/9print(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.

Solution 2:

You can do it simply by importing python modules @Fraction and @Decimal, so let see how to it works:

from decimal import Decimal from fractions import Fraction

Fraction(Decimal('8.33333333333334')).limit_denominator()

Note: the limit_denominator is was is going to simplify your fraction to the lowest value as possible. And the argument passed to the Decimal must be in quotes

Post a Comment for "Is There An Alternative To The: As_integer_ratio(), For Getting "cleaner" Fractions?"