Advertisement
Guest User

Untitled

a guest
Mar 28th, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. i=0;
  2. while i<=20
  3. disp(i)
  4. i=i+1;
  5. end
  6.  
  7. j=0;
  8. while j<=2
  9. disp(j)
  10. j=j+0.1;
  11. end
  12.  
  13. % This is technically the same as your code,
  14. % so it should have suffered from exactly the same problem.
  15. % But thanks to rearrangement of calculation,
  16. % MATLAB will calculate the number of iterations is with a division,
  17. % which gives ((20 - 0) / 0.1 + 1) == 201
  18. % Because the result value of 201 is a "small" integer,
  19. % the IEEE floating-point rounding logic will cause the result's
  20. % representation to be exactly 201, and not some plus/minus epsilon.
  21. %
  22. % I have to emphasize this is not always the case; sometimes
  23. % division can give not-exactly-integer results as well.
  24. %
  25. % This "almost, but not quite always" correct behavior led most
  26. % beginning MATLAB users into thinking that MATLAB is less susceptible
  27. % to the intricacies of finite-precision floating point arithmetics,
  28. % but OP's code example shows that MATLAB users must exercise
  29. % the same level of care as programmers of C.
  30. %
  31. for j = 0:0.1:20,
  32. disp(j);
  33. end
  34.  
  35. % Integer index range is accurate up to `(2^53) - 1`
  36. % beware of off-by-one.
  37. idx = (0:200) * 0.1;
  38. for j = idx,
  39. disp(j);
  40. end
  41.  
  42. % If you only care about the start, stop,
  43. % and the number of generated values.
  44. % Beware of off-by-one.
  45. idx = linspace(0, 20, 201);
  46. for j = idx,
  47. disp(j);
  48. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement