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?
-
Related: strange python while loop behavior with comparison.DSM– DSM2012年08月27日 18:23:15 +00:00Commented Aug 27, 2012 at 18:23
-
Many (most, actually?) base 10 numbers with a decimal component cannot be stored exactly in base 2. You are not actually dealing with the numbers .1base10 and .01base10> and thus when you are doing arithmetic with them you can't count on them being entirely accurate.chucksmash– chucksmash2012年08月27日 18:27:58 +00:00Commented Aug 27, 2012 at 18:27
3 Answers 3
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
3 Comments
Floating point round-off error. This is what I got for my last three values:
99.98000000001424
99.99000000001425
100.00000000001425
Comments
This is stemming from the inaccuracy of floating point calculations. You are relying on the == operator to compare two floating point values, which is a no-go. What you see as '100.0' might actually be something like '100.000000000314'