5

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?

2
  • Related: strange python while loop behavior with comparison. Commented 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. Commented Aug 27, 2012 at 18:27

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

3 Comments

How would you do the same task ?
@user1513100 You can use a for loop and define the number of steps you want.
@user1513100 I added a solution for your problem
6

Floating point round-off error. This is what I got for my last three values:

99.98000000001424
99.99000000001425
100.00000000001425

Comments

4

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.