Why does MATLAB not finding a element from my matrix?
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Tshikaya
am 27 Mär. 2024
Kommentiert: Walter Roberson
am 24 Jun. 2025
x = 0.4:0.01:0.5
idx = find(x==0.41)
3 Kommentare
Walter Roberson
am 24 Jun. 2025
Note that the colon operator is handled as repeated addition, so 0.4, 0.4+0.1, 0.4+0.1+0.1, 0.4+0.1+0.1+0.1 and so on. Because double precision numbers operate in binary instead of in decimal, 0.1 cannot be exactly represented, and instead each 0.1 addition adds 0.1000000000000000055511151231257827021181583404541015625
Mathworks could have chosen an impletation of (initial value) + increment * (position in the sequence minus 1), so 0.4 + [0, 1, 2, 3, 4 ...] * 0.1 ... but Mathworks did not chose that (possibly for efficiency reasons.)
Akzeptierte Antwort
Stephen23
am 27 Mär. 2024
Verschoben: Dyuman Joshi
am 27 Mär. 2024
Testing for exact equivalence of binary floating point numbers should be avoided.
Compare the values, are they actually the same? (hint: no):
x = 0.4:0.01:0.5;
fprintf('%.40f\n', x(2), 0.41)
The recommended approach is to compare the absolute difference against a tolerance:
tol = 1e-5;
abs(x(2)-0.41)<tol
More information on this topic:
This is worth reading as well:
2 Kommentare
Steven Lord
am 24 Jun. 2025
If you're using release R2024b or later, you could use the isapprox function to determine if two numbers are approximately equal.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!