I was looking at the Python documentation of fractions and trying this code:
from fractions import Fraction
>>> print("Fraction (0.5):", Fraction(0.5))
Fraction (0.5): 1/2
>>> print("Fraction (0.1):", Fraction(0.1))
Fraction (0.1): 3602879701896397/36028797018963968
>>> print(1/10)
0.1
Looking at the Fraction(0.1) result I thought it was my computer problem, but when I tried it on several computers the results were same.
My question
- is there any computational reason to choose these odd numbers
3602879701896397/36028797018963968instead of1/10just like1/2as it chosen forFraction(0.5). - more of these exist in python?
Yes, that's because that's the integer ration for the float
0.1(which can't be represented exactly with floats):If you want correct
Fractions you need to use both arguments or pass in a string:Or limit the denominator after creating it from a float (not guaranteed to work in all cases):
As for your second question: There are infinitely many rational numbers (decimal numbers that could be represented exactly as Fraction) in math but a computer uses 64bits for
doubles (the Pythonfloattype). That means only a few real numbers can have an exact representation asdouble. So there are a lot of other numbers with the same problem, just to name a few: