-1

As per my expectation .05+.01 should be equal to .06 but in python its not happening. As .05+.01 = 0.060000000000000005 and that is not equal to .06.

>>> .01+.01
0.02
>>> .02+.01
0.03
>>> .03+.01
0.04
>>> .04+.01
0.05
>>> .05+.01
0.060000000000000005  #expected .06
>>> .06+.01
0.06999999999999999  #expected .07
>>> .07+.01
0.08
>>> .08+.01
0.09
>>> .09+.01
0.09999999999999999 #expected .10
>>> 0.09999999999999999+.01
0.10999999999999999  #expected .11

what is the reason for this?

Bart Enkelaar
  • 695
  • 10
  • 21
Nullify
  • 19,655
  • 7
  • 34
  • 59

3 Answers3

9

Because Python uses IEEE-754 floating point numbers, which are not perfectly precise. The iconic example is 0.1 + 0.2 = 0.30000000000000004.

This is well documented in the Python docs.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
4

The values you're working with are floating point numbers, see also: http://docs.python.org/2/tutorial/floatingpoint.html

Bart Enkelaar
  • 695
  • 10
  • 21
4

Because 0.01 and 0.05 are not what they are looking:

>>> import decimal
>>> decimal.Decimal(0.01)
Decimal('0.01000000000000000020816681711721685132943093776702880859375')
>>> decimal.Decimal(0.05)
Decimal('0.05000000000000000277555756156289135105907917022705078125')
wimh
  • 14,791
  • 5
  • 46
  • 94
alko
  • 43,000
  • 9
  • 91
  • 100