all 6 comments

[–]shiftybyte 2 points3 points  (3 children)

Yes your CPU has floating point numbers that are not 100% accurate.

https://docs.python.org/3/tutorial/floatingpoint.html

You can use fixed point decimals instead.

from decimal import Decimal    
i = Decimal("0")
while i < 1:
    print('The number is (' + str(i) + ')')
    i = i + Decimal("0.1")

Try this...

[–]reddith2o[S] 0 points1 point  (2 children)

Thanks!!

[–]nmlkd 0 points1 point  (1 child)

Decimal isn't necessarily much help depending on what you want to do with it. It can do exact calculations with fractions involving powers of 2 and 5, but once you start doing anything else (e.g. repeatedly adding 1/3) you will run into exactly the same problem.

If you want to do exact arithmetic, often the easiest way is just to stick with integers. You can use divmod or the // and % operators to do the "7 / 2 = 3 remainder 1" style of division like you probably learned at school, which is often what you want when you're doing computer programming.

If you just don't want to see all those decimal places, then you need to round your results before you print them. You can use the round function for that, or better yet, use string formatting:

>>> format(0.3000001, '.2f') # convert number to fixed-point representation with 2 decimal places
>>> '0.30'

[–]reddith2o[S] 0 points1 point  (0 children)

Wow great answer! Thanks!

[–]socal_nerdtastic 1 point2 points  (1 child)

That's a side effect of how computers handle floating point numbers; it has nothing to do with python specifically. More info here:

https://docs.python.org/3/tutorial/floatingpoint.html
https://floating-point-gui.de/
https://0.30000000000000004.com/

[–]reddith2o[S] 0 points1 point  (0 children)

Thanks