[Tutor] Fraction - differing interpretations for number and string
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Thu Apr 16 10:51:50 CEST 2015
On 04/16/2015 07:03 AM, Jim Mooney wrote:
> Why does Fraction interpret a number and string so differently? They come
> out the same, but it seems rather odd
>
>>>> from fractions import Fraction
>>>> Fraction(1.64)
> Fraction(7385903388887613, 4503599627370496)
>>>> Fraction("1.64")
> Fraction(41, 25)
>>>> 41/25
> 1.64
>>>> 7385903388887613 / 4503599627370496
> 1.64
>
That is because 1.64 cannot be represented exactly as a float.
Try:
>>> x = 1.64
>>> format(x,'.60f')
'1.639999999999999902300373832986224442720413208007812500000000'
If you construct a Fraction from a str OTOH, Fraction assumes you meant
exactly that number.
And in fact:
>>>
Fraction('1.639999999999999902300373832986224442720413208007812500000000')
Fraction(7385903388887613, 4503599627370496)
see also https://docs.python.org/3/tutorial/floatingpoint.html for an
explanation of floating-point inaccuracies.
More information about the Tutor
mailing list