Python while loop inconstancy

python, while-loop

Solution

Because this 100.0 (result of a sum) can be bigger than 100.0 you write by hand. You should not compare float numbers for equality...

You should read this:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Possible solution:

>>> t_end = 100.0
>>> t_step = 0.01
>>> total = int(t_end/t_step)
>>> for x in itertools.accumulate((t_step for i in range(total + 1))):
    print(x)

So the last element will be: 100.01000000001426

Problem

Never seen anything like this. Simple while loop: ``` t_end = 100.0 t_step= 0.1 time = 0 while time<=t_end: time+=t_step print time ``` Last 3 printed values: ``` ... 99.9 100.0 100.1 ``` Looks right to me. Now, I change t_step to 0.01: ``` t_end = 100.0 t_step= 0.01 time = 0 while time<=t_end: time+=t_step print time ``` Last 3 printed values: ``` ... 99.98 99.99 100.0 ``` Question: Why it doesn't go for the final loop when time = t_end =100.0 ? What is the alternative solution?

Original source