我正在尝试理解MatLab中的while
语句,所以这就是我所做的:
i=0;
while i<=20
disp(i)
i=i+1;
end
正如我所料,MatLab显示的是0-20。但是有了这个:
j=0;
while j<=2
disp(j)
j=j+0.1;
end
MatLab仅显示数字0-1.9。我期待看到数字0-2;我在这做错了什么?
答案 0 :(得分:1)
您的代码不是惯用的MATLAB。
惯用语MATLAB如下所示:
% This is technically the same as your code,
% so it should have suffered from exactly the same problem.
% But thanks to rearrangement of calculation,
% MATLAB will calculate the number of iterations is with a division,
% which gives ((20 - 0) / 0.1 + 1) == 201
% Because the result value of 201 is a "small" integer,
% the IEEE floating-point rounding logic will cause the result's
% representation to be exactly 201, and not some plus/minus epsilon.
%
% I have to emphasize this is not always the case; sometimes
% division can give not-exactly-integer results as well.
%
% This "almost, but not quite always" correct behavior led most
% beginning MATLAB users into thinking that MATLAB is less susceptible
% to the intricacies of finite-precision floating point arithmetics,
% but OP's code example shows that MATLAB users must exercise
% the same level of care as programmers of C.
%
for j = 0:0.1:20,
disp(j);
end
% Integer index range is accurate up to `(2^53) - 1`
% beware of off-by-one.
idx = (0:200) * 0.1;
for j = idx,
disp(j);
end
% If you only care about the start, stop,
% and the number of generated values.
% Beware of off-by-one.
idx = linspace(0, 20, 201);
for j = idx,
disp(j);
end
答案 1 :(得分:1)
它之所以不相同的原因是base-2浮点数可以完美而精确地表示1。但它们并不代表0.1。显然,0.1值代表一个微小的高位,如0.10000000000000000001,这样当0.10000000000000000001被添加到自身20次时,超过 2.0(这是精确表示的),因此在while循环中进行测试在我们期望它通过的最后一次迭代中失败。