2

I have MATLAB code

clear all;
clc;
t=0:0.001:0.1;
N=length(t);
for n=1:N
    if t(n)==0||t(n)==0.02||t(n)==0.04||t(n)==0.06||t(n)==0.1
        fprintf('%5.5f\n',t(n));
    end
end

The result is

enter image description here

Why if t(n)==0.06, in my command window cannot displaying 0.06?

Does my MATLAB have an error? I'm using MATLAB R2014b

  • That is actually an interesting question. I've also quickly tested with `(0:0.01:0.1) == x` and can verify that `x=0.06` and `x=0.09` are incorrect. Machine precision error? – mimocha Mar 16 '21 at 05:08
  • Never, ever, ever do equality comparison with floating-point numbers. They are approximations – Cris Luengo Mar 16 '21 at 05:47

1 Answers1

1

It's a numerical error because the 0.001 increments will not be precisely 0.001 under the hood.

The same thing happens in 2020b:

>> t = 0:0.001:0.1;
>> t(61)

ans =
   0.0600

>> t(61) == 0.06

ans =
   logical
   0

If you want to compare floats, use some kind of tolerance like eps instead of ==:

>> (t(61) - 0.06) < eps

ans =
   logical
   1
tdy
  • 36,675
  • 19
  • 86
  • 83