フィルターのクリア

My script sees the value 2 different then 2.0000 which is a problem

1 回表示 (過去 30 日間)
Ibrahim DAWI
Ibrahim DAWI 2018 年 6 月 19 日
コメント済み: Ibrahim DAWI 2018 年 6 月 19 日
hello, i am facing a problem in my script, where MATLAB is seeing the value A=2.000 > B=2 . i have checked the value A to see if it belongs to a value slightly larger then 2 by applying
floor(A) and ceil(A) which both give a result of 2.
what is the problem in your opinion and how could i fix it? Thank you!

採用された回答

Guillaume
Guillaume 2018 年 6 月 19 日
You cannot compare floating point numbers obtained through different methods with ==. This is true for all computer languages. This is due to the fact that many numbers cannot be represented exatly as floating point numbers (0.1 is one of them) and therefore small errors accumulate differently depending on the operations you perform.
For more details, see why is 0.3-0.2-0.1 not equal to zero. From your floor test you can see than optimal_distance is slightly smaller than 2 while temp_distance is either exactly 2 or slightly larger than 2. By slightly, we're talking of a difference most likely around or smaller than 1e-16.
The proper way to compare floating point number is to compare their difference to a small enough tolerance for your calculatios. In your case:
abs(optimal_distance - optimal_distance) < 1e-10
is probably appropriate.
  1 件のコメント
Ibrahim DAWI
Ibrahim DAWI 2018 年 6 月 19 日
You are right, thank you for your answer it was very helpful!

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

その他の回答 (1 件)

Sayyed Ahmad
Sayyed Ahmad 2018 年 6 月 19 日
編集済み: Sayyed Ahmad 2018 年 6 月 19 日
Look at Operator Precedence in matlab.
A=2000;
B=2;
C=A>B;
  4 件のコメント
Dennis
Dennis 2018 年 6 月 19 日
try:
if abs(temp_distance(9)-optimal_distance(9))<0.001
Guillaume
Guillaume 2018 年 6 月 19 日
The tolerance (the 0.001, see discussion in my answer) needs to be defined appropriately for the magnitude of the numbers compared and the possible accumulated error of the calculations that produced these numbers.
As we don't know anything about these calculations, we can't be sure of anything but if 0.001 out of 2 is around the magnitude of the accumulated error I'd say that you've got big problems. It is most likely that a smaller tolerance would be more appropriate.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by