Incorrect evaluation of logic statement

5 views (last 30 days)
Tommy
Tommy on 22 May 2014
Commented: Sara on 22 May 2014
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
Tommy
Tommy on 22 May 2014
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 on 22 May 2014
The error should be in the order of x*eps not that big. Can you attach your code?

Sign in to comment.

Answers (1)

the cyclist
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.

Community Treasure Hunt

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

Start Hunting!