3

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

codeepic
  • 3,723
  • 7
  • 36
  • 57
Aniket Navlur
  • 962
  • 1
  • 11
  • 22
  • 4
    This is well explained in Python's tutorial: [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3.6/tutorial/floatingpoint.html) – Thierry Lathuille Oct 19 '18 at 13:49

2 Answers2

3

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."

asthasr
  • 9,125
  • 1
  • 29
  • 43
1

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.

Håken Lid
  • 22,318
  • 9
  • 52
  • 67