0

So, i'm trying to increment a variable by 0.01

On the 6th iteration, the total seems to be getting incremented by more than 0.01

Can anybody please explain what's going on?

I'm trying to loop through minutes and hours, adding the degrees that the hour and minute hand will move forward.

2 Answers2

0

That is because how computers store floating point values in memory. Floating point values are converted to binary.

refer to this documentation to know how floating point numbers are stored in python: https://docs.python.org/3/tutorial/floatingpoint.html

To avoid this issue, you can use a different approach to loop through the values, such as using integers and dividing by 10. For example:

a = 0
while(a < 100):
    print(a/10)
    a += 1
-1

is it occurs only on the 6'th iteration or on every iteration prior to the 6'th? try this out:

   for i in range(x): # x is the number of iterations
    num += 0.01  
Roy BA
  • 1
  • 3