Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- i=0;
- while i<=20
- disp(i)
- i=i+1;
- end
- j=0;
- while j<=2
- disp(j)
- j=j+0.1;
- end
- % 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement