Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python while loop inconstancy

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?

like image 479
user1513100 Avatar asked Aug 27 '12 18:08

user1513100


1 Answers

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

like image 175
JBernardo Avatar answered Sep 30 '22 00:09

JBernardo