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
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
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
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
Tommy 2014 年 5 月 22 日
Thanks for the answers. Initially, x=123.321 exactly but when I say x=x-100, I get x=23.32099... That seems like a pretty serious issue, and not one I've encountered in any other mathematics package. I know MATLAB is used in industry where precision is needed, so surely there's a way to fix this. Perhaps a different data type?
Sara
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
the cyclist 2014 年 5 月 22 日

0 投票

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 ExchangeTime Series Events についてさらに検索

質問済み:

2014 年 5 月 22 日

コメント済み:

2014 年 5 月 22 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by