Incorrect evaluation of logic statement
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
Sean de Wolski
on 22 May 2014
What are you doing after the displays in the loop? Please provide a whole minimal working example.
Geoff Hayes
on 22 May 2014
But is x really 1.0000e-03 or is it just the rounded up number that is being displayed. Would be interesting to see what the following returns:
fprintf('x=%.24f\n',x);
for 24 decimal places...
Sara
on 22 May 2014
If you type in the command window
format longg
you may discover that your variables are not what is shown with the disp command.
Tommy
on 22 May 2014
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.
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!