strange behaviour of STEP in FOR loop

Hi

Run this program to see what I mean. Seems like a bug to me ?

Erik

-- step error

-- Use this function to perform your initial setup
function setup()
    
    font("AmericanTypewriter")
    
    displayMode(FULLSCREEN)
    
end

-- This function gets called once every frame
function draw()

    background(0, 0, 0, 255)
    stroke(255, 255, 255, 255)
    strokeWidth(2)
    fontSize(30)

    blockwidth = WIDTH / 6    
    blockheight = HEIGHT / 10

-- first row: step = 1

    y = 6 * HEIGHT / 8
    step = 1
    
    fill(255, 49, 0, 255)
  
    for i = 0, 5, step do
        x = i * blockwidth
        rect(x, y, blockwidth, blockheight)
    end
    
    fill(0, 0, 0, 255)
    text("STEP == "..step, WIDTH / 2, y + blockheight / 2)
    

-- second row: step = 0.5

    y = 5 * HEIGHT / 8
    step = 0.5

    fill(255, 49, 0, 255)

    for i = 0, 5, step do
        x = i * blockwidth
        rect(x, y, blockwidth, blockheight)
    end
    
    fill(0, 0, 0, 255)
    text("STEP == "..step, WIDTH / 2, y + blockheight / 2)
    


-- third row: step = 0.2

    y = 4 * HEIGHT / 8
    step = 0.2

    fill(255, 49, 0, 255)

    for i = 0, 5, step do
        x = i * blockwidth
        rect(x, y, blockwidth, blockheight)
    end
    
    fill(0, 0, 0, 255)
    text("STEP == "..step, WIDTH / 2, y + blockheight / 2)
    

-- fourth row: step = 0.05

    y = 3 * HEIGHT / 8
    step = 0.05

    fill(255, 49, 0, 255)

    for i = 0, 5, step do
        x = i * blockwidth
        rect(x, y, blockwidth, blockheight)
    end
    
    fill(0, 0, 0, 255)
    text("STEP == "..step, WIDTH / 2, y + blockheight / 2)
    

-- remark

    fill(222, 117, 10, 255)
    fontSize(20)
    
    y = 2.5 * HEIGHT / 8
    text("In a loop for i = 0 to 5 the code between DO and END is repeated", WIDTH / 2, y)
    
    y = y - HEIGHT / 16
    fontSize(30)
    text("until  AND INCLUDING  i = 5.", WIDTH / 2, y)
    
    y = y - HEIGHT / 16
    fontSize(20)
    text("This is also the case if STEP is set to a dividable part of the range", WIDTH / 2, y)   
    
    y = y - HEIGHT / 16
    fontSize(20)
    text("but in this example Codea skips the last block when step = 0.05    ? ? ?", WIDTH / 2, y)   
    


end

Hello @eriksw. It is not a bug in Codea or Lua. It is the result of the fact that certain decimal fractions cannot be represented precisely in binary. See here, for example. By the time you have added 0.05 99 times, there is a small rounding error (in the binary representation) that takes the next addition above 5.

-- Rounding error

function setup()
    t = 0
    for i = 1, 100 do
        t = t + 0.05
    end
    print(t - 5) -- Output: 9.53674e-07
end

function draw() background(0) end

You can avoid this by multiplying your loop variable by 20 so you can step by 1, then dividing by 20 when using the number inside the loop

ok thanks guys