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

Viewed 46

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

1 Answers

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
Related