Connect with users of Wolfram technologies to learn, solve problems and share ideas
Mark as an Answer
3 Total Likes
Follow this post
Share this post:
Why does this For-loop iterate once less than expected?
10 years ago
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.
10 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.
Reply to this discussion
in reply to
Community posts can be styled and formatted using the
Tag limit exceeded
Note: Only the first five people you tag will receive an email notification; the other tagged names will appear as links to their profiles.
Add a file to this post
Follow this discussion
Be respectful. Review our
to understand your role and responsibilities.
Wolfram|Alpha Notebook Edition
Volume & Site Licensing
Enterprise Private Cloud
Service Plans Benefits
Wolfram Language Documentation
Wolfram Language Introductory Book
Get Started with Wolfram
Fast Introduction for Programmers
Fast Introduction for Math Students
Webinars & Training
Connected Devices Project
Wolfram Data Drop
Wolfram + Raspberry Pi
. All rights reserved.
Learn how »