Normal / gaussian distribution in lua

Here's a function that generates random numbers between 0 and 1 in a gaussian distribution centred around 0.5

-- returns approx gaussian distribution centred around 0.5 [0->1]
function normal_random()
    -- box-muller method
    local u = math.random()
    local v = math.random()
    local r = math.sqrt(-2.0 * math.log(u,10)) * math.cos(2.0 * math.pi * v)
    r /= 4
    r += 0.5
    -- values out of range create anomalies at 0 and 1. redistribute the values uniformly
    if r < 0 or r > 1 then r = math.random() end
    return r
end

here's a function that tests it and what the image looks like

function test_normal_random()
    img_normal = img.new(400,240)
    points = table.create(400,0)
    for x = 1, 400 do
        points[x] = 0
    end
    local max = 0
    for i = 1, 50000 do
        local r = math.floor(1 + normal_random() * 399)
        points[r] += 1        
        max = math.max(max, points[r])
    end
    local m = 240/max
    gfx.pushContext(img_normal) do
        for x = 1, 400 do
            gfx.drawLine(x-1, 240, x-1, 240-points[x]*m)
        end
    end gfx.popContext()
    return img_normal
end

2 Likes