I was experimenting with the IDLE Python 3.4.0 shell, and executed the following code.
>>> from decimal import *
>>> getcontext().prec = 500
>>> e = Decimal(2.4)
>>> print(e)
2.399999999999999911182158029987476766109466552734375
As you can see, I set the variable e
equal to exactly 2.4, nothing more, nothing less. However, when I printed e
, instead of printing 2.4
or 2.400000...
, it printed what you see above. I then tried changing the getcontext().prec
to 5, and it still printed the exact same results. Now, to repeat my experiment, I tested it with a whole number, and then another decimal number.
>>> f = Decimal(10)
>>> print(f)
10
>>> g = Decimal(10.1)
>>> print(g)
10.0999999999999996447286321199499070644378662109375
The strange string of decimal numbers is only printed whenever I assign a non-whole number with the decimal class. Finally, I tested this with floating point numbers.
>>> h = float(2.4)
>>> print(h)
2.4
>>> i = float(10.1)
>>> print(i)
10.1
Why does the decimal class cause these odd strings of decimals instead of the exact number?