Two dependent switch on float in a loop.

1 次查看(过去 30 天)
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?

回答(1 个)

Jan
Jan 2017-5-13
编辑:Jan 2017-5-13
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.

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by