Two dependent switch on float in a loop.

2 views (last 30 days)
Peiyuan ZHU
Peiyuan ZHU on 13 May 2017
Edited: Jan on 13 May 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?

Answers (1)

Jan
Jan on 13 May 2017
Edited: Jan on 13 May 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.

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!