Message Boards Message Boards

Why does this For-loop iterate once less than expected?


I've just started using Mathematica and encountered some weird effect:
i = 0;
For[i = 0, i <= 20, i = i + 0.01];
instead of the expected
i.e. the loop is iterated one time less than it should. That snippet is a reduced form of what I actually used but reproduces the point; if a body is added it would also only execute with i==19.99 for the last time.
That seems to be true for all increments 10^-n, n>1 but no other value that I tested. Is anybody able to give some insight as to whether this is a bug or rather related to some  precision constraints or a rather dumb misunderstanding of mine and how I could fix it?
In case it matters, this is on 9.0.1.
POSTED BY: Benedikt A
3 years ago
You'll notice that after running your code, i == 20 is False.    Actually you'll have 20.000000000000327 > 20.0.  This is not unique to Mathematica, you'll find it in almost any language.   It's important to be aware of this when doing any kind of programming involving floating point numbers.

The reason is the accummulated errors from the repeated addition, and the fact that 0.01 is not exactly representable in binary (the way the computer stores floating point numbers), so the actual value is slightly larger.

Mathematica uses machine precision floating numbers by default for performance reasons, but you can do better: try i = i + 0.01`10 instead, which will use Mma's built in arbitrary precision arithmetic with 10 digits of precision, and it'll do precision tracking too.  Or use exact numbers:  i = i + 1/100

The best thing though is not to use For loops at all as a beginner.  Use Table, Map, Fold, etc. or use Do for the "standard" for loops.
POSTED BY: Szabolcs Horvát
3 years ago

Group Abstract Group Abstract