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

1 vue (au cours des 30 derniers jours)
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)

Réponse acceptée

Walter Roberson
Walter Roberson le 24 Déc 2016
Modifié(e) : Walter Roberson le 12 Jan 2017
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 commentaire
Robert Garton
Robert Garton le 24 Déc 2016
Thanks Walter you were spot on. The value ended up being 0.000039999999999999434065981602.
Thanks for your help.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by