why is simulink matlab function block failing to evaluate a < operator correctly

1 回表示 (過去 30 日間)
I have a simply if else statment using <= and < operators. I have a situation where my code is incorrectly evaluating "remainder < Tfs*2" as true when the two values are 0.00004.
elseif (Tfs <= remainder & remainder < Tfs*2)
remainder < (Tfs*2) % this evaluates to 1
fprintf('%.15f, %.15f\n', remainder, Tfs*2); % output is 0.000040000000000, 0.000040000000000
vector = 1;
elseif (Tfs*2 <= remainder && remainder < Tfs*3)

採用された回答

Walter Roberson
Walter Roberson 2016 年 12 月 24 日
編集済み: Walter Roberson 2017 年 1 月 12 日
0.000040000000000 is not enough digits of printout to see whether the two are equal or not.
4.00000000000000032721221565612523818344925530254840850830078125e-05
and
3.9999999999999996495858578526849669287912547588348388671875e-05
will both print out as 0.000040000000000 but are not equal.
You should either grab num2strexact from the File Exchange or you should print out
remainder - Tfs*2
You should also consider assigning Tfs*2 to a variable so that you avoid evaluating it multiple times. Floating point values calculated by even slightly different methods are permitted to give different results.
  1 件のコメント
Robert Garton
Robert Garton 2016 年 12 月 24 日
Thanks Walter you were spot on. The value ended up being 0.000039999999999999434065981602.
Thanks for your help.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by