Filter löschen
Filter löschen

Two dependent switch on float in a loop.

2 Ansichten (letzte 30 Tage)
Peiyuan ZHU
Peiyuan ZHU am 13 Mai 2017
Bearbeitet: Jan am 13 Mai 2017
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?

Antworten (1)

Jan
Jan am 13 Mai 2017
Bearbeitet: Jan am 13 Mai 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.

Kategorien

Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by