0

I was using a simple for loop to add numbers but I found a strange result when adding float.

Can you explain why I have the following output ?

1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
1.6000000000000005
1.7000000000000006
1.8000000000000007
1.9000000000000008
2.000000000000001
2.100000000000001
2.200000000000001
2.300000000000001
2.4000000000000012
2.5000000000000013
2.6000000000000014
2.7000000000000015
2.8000000000000016
2.9000000000000017
3.0000000000000018
3.100000000000002
3.200000000000002
3.300000000000002
3.400000000000002
3.500000000000002
3.6000000000000023
3.7000000000000024
3.8000000000000025
3.9000000000000026

This is based on Anaconda Spyder

a = 1

for i in range(1,30):
    a = a+0.1
    print(a)
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Rick Zhang
  • 69
  • 1
  • 4

1 Answers1

1

It's a known limitation of floating point arithmetic, computers cannot store infinitely precise floating point numbers. See python docs.

asikorski
  • 882
  • 6
  • 20