Incorrect evaluation of logic statement
显示 更早的评论
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 个评论
Sean de Wolski
2014-5-22
What are you doing after the displays in the loop? Please provide a whole minimal working example.
Geoff Hayes
2014-5-22
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
2014-5-22
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
2014-5-22
Sara
2014-5-22
The error should be in the order of x*eps not that big. Can you attach your code?
回答(1 个)
the cyclist
2014-5-22
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!