フィルターのクリア

Why find doesn't work for some number?

1 回表示 (過去 30 日間)
mariem farhat
mariem farhat 2015 年 10 月 23 日
コメント済み: Steven Lord 2021 年 5 月 27 日
Hello,
I have the following code
if true
for i = 0:0.1:2
k = find (A==i);
disp(k);
end
This code works but for some number it doesn't work. For example, i=0.6 and 0.7. But when I wrote find(k==0.6) it works!!!
What is the problem? Any idea please

回答 (1 件)

Adam
Adam 2015 年 10 月 23 日
編集済み: Adam 2015 年 10 月 23 日
Testing exact equality between double-precision data is un-safe in general. Due to the representation of these numbers a test for absolute equality can fail because of a difference of 0.000001 that you don't see in the variable editor or command window.
If your values such as 0.6 in the array A are the result of some calculation then this will often be the case that they are not precisely 0.6, but may instead be 0.600000000001
  6 件のコメント
Rik
Rik 2021 年 5 月 27 日
You can either use ismembertol, uniquetol, etc, or you can do something like this:
% instead of A==B
abs(A-B)<=tol
Steven Lord
Steven Lord 2021 年 5 月 27 日
Close only counts in horseshoes, hand grenades, and comparing floating-point numbers. The tolerance controls what is "close enough" to a match to count as a match.
x = 1;
y = 2;
If you compare x and y with a tolerance of 5 ("close enough" being within 5 units) then x and y match.
doTheyMatch = abs(x-y) <= 5
doTheyMatch = logical
1
If you compare x and y with a tolerance of 0.5 ("close enough" being within 0.5 units) then they do not.
doTheyMatch = abs(x-y) <= 0.5
doTheyMatch = logical
0
If you used a tolerance of 0 you're saying "close enough isn't good enough, it has to be an exact match down to the last bit" and in that case sometimes numbers that look like they match don't actually match.
tenth = 0.1; % Not exactly one tenth, but close
z1 = tenth + tenth + tenth
z1 = 0.3000
z2 = 0.3
z2 = 0.3000
doTheyMatch = abs(z1-z2) <= 0 % essentially equivalent to z1 == z2
doTheyMatch = logical
0
howFarApart = abs(z1-z2) % very small but not 0
howFarApart = 5.5511e-17

サインインしてコメントする。

カテゴリ

Help Center および File ExchangePole and Zero Locations についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by