Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to the: as_integer_ratio(), for getting "cleaner" fractions?

Tags:

python

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?

like image 712
Siebe Albers Avatar asked Jan 21 '26 03:01

Siebe Albers


1 Answers

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.

like image 78
user2357112 supports Monica Avatar answered Jan 22 '26 15:01

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!