Matlab accuracy (when 1-1~=0)

Below please find a screenshot from a sample script that really puzzles me.
When defining simple variables and then substracting them there appear to be tiny error (3e-18) that comes in with surprising results.
It would be great if somebody could explain why this happens and how to avoid it.
w=0.026
b=0.024
i=0.001
w-0.026
b-0.024
i-0.001
w-(b+2*i)
w==(b+2*i)

Answers (1)

It's float operation universe. :)
w=0.026;
b=0.024;
i=0.001;
w-0.026;
b-0.024;
i-0.001;
Instead of:
w == (b+2*i)
ans = logical
0
Use:
abs(w - (b+2*i)) <= 1e-5 % You could use 1e-17 and still will receive a true logical value
ans = logical
1

5 Comments

w=0.026;
b=0.024;
i=0.001;
Then you wrote these lines, which do effectively nothing in MATLAB, except do a computation, and then dump it directly into the bit bucket, not even displayed in the command window.
w-0.026;
b-0.024;
i-0.001;
I could have removed the semi-colons, as else, the result is not even displayed. But even then w - 0.026 will still be EXACTLY zero.
(w-0.026) == 0
ans = logical
1
(b-0.024) == 0
ans = logical
1
(i-0.001) == 0
ans = logical
1
As you can see, in each case, the result is exactly zero. That is to be expected. It is only the computation that produces a non-zero result due to floating point arithmetic.
w - (b + 2*i)
ans = -3.4694e-18
Thanks John. 'Floating point arritmetric' is a great pointer. I am aware that the above script does absolutely nothing. I created it purely to highlight an issue I encountered in a more complex data processing script where I relied on the logic w>=(b+2i) to return a '1' which it didn't. I have found a work around.
Thanks Eric, that works!
1/10 is not exactly representable in finite binary floating point -- for the same mathematical reason that 1/3 is not exactly representable in finite decimal.
Suppose we were working in decimal and said 1/3 = 0.3333333333 then if we add those together 3 times we get 0.9999999999 -- which in decimal is distinct from 1.0 . In decimal you need a literally infinite number of digits of precision for the 0.3-repeated added together 3 times to produce a result that is mathematically exactly equal to 1 .
So the problem is not exactly with the fact that MATLAB uses binary: the problem is that if you choose any finite-length fixed-point base, there will always be rational fractions that cannot be exactly represented in finite length. It is an unfortunate mathematical limitation of the Universe.
Thank you so much Walter for the clear explanation.

Sign in to comment.

Products

Release

R2021b

Asked:

on 20 Sep 2022

Commented:

on 21 Sep 2022

Community Treasure Hunt

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

Start Hunting!