Logical Indexing With LinSpace Issues
9 次查看(过去 30 天)
显示 更早的评论
Logical indexing is missing an equivalence in a linspace array. I have absolutely no idea why or how to fix this. I'm running MATALB R2022b on Windows 11.
Any ideas or help or explanation would be appreciated.
Here is how you can recreate my issue:
X = linspace(0.2,3,29); %Creates an array going from 0.2 -> 3 via steps of 0.1. So 1.3 is in it.
disp(X(12))
flag = (X == 1.3);
any(flag) %Yet for some reason 1.3 isn't detected.
%Just to be absolutely sure I'm not mad
disp(X(12))
X(12) == 1.3
% Yet other non-integers still work!
flag = (X == 1.1);
any(flag)
2 个评论
Stephen23
2023-3-8
"Any ideas or help or explanation would be appreciated."
This is a completely expected result with binary floating point numbers:
This is worth reading as well:
采纳的回答
Star Strider
2023-3-8
format long
X = linspace(0.2,3,29) %Creates an array going from 0.2 -> 3 via steps of 0.1. So 1.3 is in it.
disp(X(12))
flag = (X == 1.3);
any(flag) %Yet for some reason 1.3 isn't detected.
Check_Equality = 1.3 - X(12)
%Just to be absolutely sure I'm not mad
disp(X(12))
X(12) == 1.3
% Yet other non-integers still work!
flag = (X == 1.1);
any(flag)
The‘Check_Equality’ assignment demonstrates that the two numbers are actually not equal.
You’re not mad! You just haven’t been introduced to the subtle mysteries of floating-point numeric repreesentation.
.
2 个评论
更多回答(1 个)
Chris
2023-3-8
编辑:Chris
2023-3-8
This looks like a problem of computer precision. Double-precision floating point numbers in matlab (and floating-point numbers in general) a̶r̶e̶ ̶n̶o̶t̶ ̶e̶x̶a̶c̶t̶ (edit: are a finite set of discrete values, so they are usually unlikely to exactly match the value we see displayed)
X = linspace(0.2,3,29);
Y = 0.2:0.1:3;
% X(11)==1.2 because the result of the linspace division
% is the same as the double representation for 1.2
sprintf('%.60f\n%.60f',X(11),Y(11))
% X(12) doesn't equal the double for 1.3.
sprintf('%.60f\n%.60f',X(12),Y(12))
You can use other comparison operators to test rough equivalence, e.g., (X(12)-1.3) < 1e-14
Here's a bit more information, if you're interested.
4 个评论
Walter Roberson
2023-3-9
No, the opposite. Each time you add two floating point numbers, the round-off error can increase (unless the sequence of operations has been carefully chosen.) The error for 0.1, 0.1+0.1, 0.1+0.1+0.1 is greater than for (1:3)/10
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!