For loop and impact of "step" value

I have a question regarding the for loop:

If you inspect the examples below you will recognize a different behavior.

    for i=1, 2, 0.1 do
        print(i)            -- value "2" is not reached
    end
    
    for i=1, 10, 1 do
        print(i)            -- value "10" is reached
    end

Funny enough, the behaviour seems to depend on the value of the “step” value.

    for i=1, 10, 0.25 do
        print(i)            -- works
    end

This is really puzzling me. Maybe someone knows what is going on here?

CrazyEd, it must not be able to represent 2 as an exact value. You see 2 on the screen, but it really means 1.9999999

Some integer values can be represented exactly, some can’t. To know which is which you’d have to get into details of the floating point representation.

I’m actually not sure if for i=i,j,1 always works or not now that I think about it.

actually for x=i,j,1 should always work because integers are exact. In your example it’s not the 2 that can’t be represented exactly, it’s probably the 0.1 increment that can’t.

It does seem crazy… especially when the following does print the final 2:

for i=1,2.000001,.1 do
        print(i)
end

Edit: it appears the issue is floating point inaccuracy (discussed here):

http://stackoverflow.com/questions/7237773/strange-for-loop-problem

I was just searching for that too :slight_smile:

http://cs.furman.edu/digitaldomain/more/ch6/dec_frac_to_bin.htm

.1 is .1 (decimal) = .00011001100110011 . . . (base 2) .

Many thanks for your answers. This leads me to the conclusion to avoid using the step option in a for loop. Better doing that in an old fashioned way: use a pure integer loop, and calculate the required step inside the loop. This will guarantee that length of vectors is 100% predictable.