-1

This is the code I typed:

s=0.0
for i in range(10):
    s+=0.1
    print(s)

And this was the output:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Can someone please explain why it becomes 0.7999999999999999 after 0.7?

P.S : I know why it became 0.300...004

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
san234
  • 1
  • 2
  • My question wasn't about 0.30000000000000004. It was about how 0.7 became 0.7999999999999999. – san234 Mar 28 '17 at 05:28

1 Answers1

0

Partly because the decimal system is base-10 and the binary system is base-2, some decimal numbers can’t be represented exactly in binary, which introduces rounding errors into the code. Python uses floating point arithmetic which tends to introduce minor errors like this. The less bits used, the more these errors tend to occur (32-bit is less accurate than 64-bit etc).

https://en.wikipedia.org/wiki/Floating-point_arithmetic

Has a great deal of information on this subject if you are interested in further reading. There is a lot more to this issue than I could feasibly deal with in one answer.