Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fractions in Python for floating point numbers [duplicate]

Tags:

python

Why are the numerators and denominators of the fraction larger when number passed as float?

>>> from fractions import Fraction
>>> 
>>> a = Fraction(2.34)
>>> print(a)
658651445502935/281474976710656
>>> 
>>> 658651445502935/281474976710656
2.34
>>> 
>>> b = Fraction('2.34')
>>> print(b)
117/50
>>> 

PS: It's python on python IDLE

like image 996
Aniket Navlur Avatar asked Mar 01 '26 23:03

Aniket Navlur


2 Answers

Floating point numbers are not exact representations of the decimal value you are attempting to pass. There are imprecisions. Consider reading an article like "What Every Programmer Should Know About Floating-Point Arithmetic."

like image 199
asthasr Avatar answered Mar 04 '26 12:03

asthasr


Floating point numbers are already rational numbers, so the conversion to the Fraction type comes directly from the underlying representation of the float.

(2.34).as_integer_ratio() == (658651445502935, 281474976710656)

But not all fractions (rational numbers) can be represented accurately as floating point numbers. I will not explain floating point in detail (others have already postet links to excellent explanations), but one important limitation is that the denominator always is a power of 2.

In the case of 2.34 = 117/50, Note that 50 is not a power of 2. But our denominator in the float fraction is 281474976710656, which is 248.

When you pass a string to Fraction(), the value will be parsed as a base 10 number and will not be converted to an intermediate floating point type. Therefore the Fraction will be more accurate, since the denominator can be any integer, not only powers of 2.

like image 30
Håken Lid Avatar answered Mar 04 '26 12:03

Håken Lid