I have just been bitten by an odd floating point comparison issue. At the heart of the issue is that I expected to get true for the following test
x = 0:0.1:0.3;
y = 0:0.1:0.4;
isequal(x, y(1:end-1))
Instead
x - y(1:end-1)
ans =
1.0e-16 *
0 0 -0.2776 -0.5551
The help for COLON says J:D:K is the same as [J, J+D, ..., J+m*D] where m = fix((K-J)/D) which I think supports my expectation. It is not quite right since for 0:0.1:0.3, fix((K-J)/D) is 2. I thought possibly COLON was just doing a linspace, but I also get false for
z = linspace(0, 0.3, 4);
isequal(x, z)
Interestingly, for all the cases I have tried I get true for
a = 0;
b = 0.3;
c = 0.1;
x = a:c:b;
isequal(x(end), b)
suggesting COLON somehow fixes the ends, but not in the same way that LINSPACE does.
How does COLON work?
3 Comments
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/53912-floating-point-accurarcy-and-colon#comment_111530
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/53912-floating-point-accurarcy-and-colon#comment_111530
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/53912-floating-point-accurarcy-and-colon#comment_111531
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/53912-floating-point-accurarcy-and-colon#comment_111531
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/53912-floating-point-accurarcy-and-colon#comment_111535
Direct link to this comment
https://it.mathworks.com/matlabcentral/answers/53912-floating-point-accurarcy-and-colon#comment_111535
Sign in to comment.