Incorrect evaluation of logic statement
5 views (last 30 days)
Show older comments
I'm new to MATLAB so I might be missing something obvious. I've read that MATLAB has floating point issues but this involves comparing two number with only a few digits.
Inside a while loop I have:
disp(x)
disp(B)
disp(ind)
x>=B^(ind+1)
after some loops I get:
1.0000e-03
10
-4
ans = 0
Entering the expression in the command window:
>> 1.0000e-03>=10^(-4+1)
ans =
1
How do I get correct operation inside the while loop? Are there separate settings for precision inside loops? Thanks in advance.
5 Comments
Sara
on 22 May 2014
The error should be in the order of x*eps not that big. Can you attach your code?
Answers (1)
the cyclist
on 22 May 2014
I sincerely hope that you will not be offended by this, but the way you have phrased your question (and its title) indicates that you don't have a very sophisticated knowledge of floating point arithmetic in general. I can assure you that MATLAB is accurately evaluating the logical statement in both cases, but I am sympathetic that this can be hard to understand.
As Sean mentions, actual code that exhibits the difference would be helpful. But the gist is that x is probably not exactly 1.0000e-3, or B is not exactly 10, etc, inside your for loop (even if you expect them to be).
Your comparison is reliant on a condition that is finely tuned. For example,
x = 1.e-3
B = 10
ind = -4
x>=B^(ind+2*eps+1)
will give a result of 0, because I added just a tiny offset (approximately that of round-off error) to your equation.
If you display your variable with
format long
you may get a better handle on what is going on. Here is a good starting point for reading more about the trickiness of floating point arithmetic.
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!