MATLAB: Bug in matlab R2012b version

not a bugprecision

Hello,
I use the MATLAB R2012b version and when I try this:
0.5:0.1:0.8 the answer is:
ans =
Columns 1 through 3
5.000000000000000e-01 6.000000000000000e-01 7.000000000000001e-01
Column 4
8.000000000000000e-01
Why the third term is not strictly equal to 0.7? Furthermore when I try 0.5:0.1:0.9 the bug disappears!
Do you have an answer? Note: (as a reminder go to "HOME", "Preferences" and select "long e")
Thanks in advance

Best Answer

Not really an answer, but a suggestion in the light of the observations made in the question and in other answers.
In general, I think it makes sense to use the colon operator only for integer cases. That is, it's good for iteration counting ( for i = 1:10 ) and array indexing ( x(3:17) ) but it's not so suitable for getting a linear space when there are non-integers involved.
In such cases, you get more control and predictability using linspace. The downside is that you have to compute the number of elements in the sequence yourself, but this is really an advantage because you choose what is going on. So instead of
0.5 : 0.1 : 0.8
you'd use
linspace( 0.5, 0.8, round((0.8 - 0.5)/0.1) + 1 )
In general, the increment will not be exactly divisible into the space between the end points. The big advantage of using linspace is that it makes you think through exactly what you want to do about this: adjust the end points, or adjust the increment.
Of course, there will be exceptions to this "colon for integers only, otherwise linspace" rule, but I think it's a good starting position.
[Incidentally, I have a guess about what is going on with the colon operator. Rounding errors mean that in a sequence like 0.5:0.1:0.8 you can't predict whether the result will include 0.8 at the end or not, because 0.5 + 3*0.1 might evaluate to just less than 0.8. I suspect the colon operator tries to make this predictable by tweaking the increment a little bit. Which might be fine if it was documented.]