Question

w = 0 
while w <= 1.0:
    print str(int(w*10))
    w += 0.1

Why this answer is 0 1 2 3 4 5 6 7 7 9 9 where is 8 and 10?

i just use

print str(int(0.8*10))

It print '8'

Thank u! :D

Was it helpful?

Solution

Because .1 cannot be represented in binary, so there is some round off error. Let's try a different script:

w = 0 
while w <= 1.0:
    print repr(w)
    w += 0.1

What does it print?

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

OTHER TIPS

That's because of the design of floating points. 0.1 is a fraction, that cannot be represented exactly as binary (base 2) fraction.

See for yourself, what I mean:

I removed the conversion to int and the uneccessary conversion to str:

w = 0
while w <= 1.0:
  print(w*10)
  w += 0.1

prints:

0
1.0
2.0
3.0000000000000004
4.0
5.0
6.0
7.0
7.999999999999999
9.0
9.999999999999998

as converting a float to int always just cuts off the part after the point, it will print 7 and 9 twice.

See http://docs.python.org/2.7/tutorial/floatingpoint.html#tut-fp-issues for more information on this. Especially: http://docs.python.org/2.7/tutorial/floatingpoint.html#representation-error

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top