Two dependent switch on float in a loop.
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
for t=0.2:0.1:4
fcn(t);
end
function fcn(t)
for x=1:3
fcn1(x,t)
end
end
function fcn1(x,t)
switch t
case 0.2
y=3;
case 0.3 % why is this skipped when t = 0.3?
y=2;
case 0.4
y=1;
otherwise
error('t out of range');
end
switch y
case 1
z=1;
case 2
z=2;
case 3
z=3;
otherwise
error('y out of range');
end
z = z+x;
end
What's going on when t = 0.3? The switch case misjudges?
0 Commenti
Risposte (1)
Jan
il 13 Mag 2017
Modificato: Jan
il 13 Mag 2017
Wow, the most frequently asked question again.
why is this skipped when t = 0.3
Because t is not 0.3 . You see that Matlab is convinced, that this case does not happen. Try it:
0.2 + 0.1 - 0.3
% >> 5.55111512312578e-17
Decimal numbers do not have an exact representation in the binary IEEE754 format, which is used for computations in Matlab and otehr programming languages. Therefore you get rounding effects due to the limited precision. See also:
1e17 + 1 - 1e17
When you want to perform numerical computations, it is very essential, that you understand what happens here and therefore this topic is handled in the first lesson and in the first chapter of books about numerics.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!