Skip to content

Instantly share code, notes, and snippets.

@b0mbie
Created May 14, 2022 14:25
Show Gist options
  • Select an option

  • Save b0mbie/f9671b8414a0e438b1cc735ec5535a61 to your computer and use it in GitHub Desktop.

Select an option

Save b0mbie/f9671b8414a0e438b1cc735ec5535a61 to your computer and use it in GitHub Desktop.
Iterative mean function for Lua
return function imean(m, v, i)
return ((m * i) + v) / (i + 1)
end
local imean = require "imean"
-- define the values to find the means of
local values = { 2, 3, 4, 5 }
-- get regular mean
local m = 0
for i,x in ipairs(values) do m = m + x end
m = m / #values
-- get iterative mean
local im
for i,x in ipairs(values) do
if i == 1 then
im = x
else
im = imean(im, x, i - 1)
end
end
-- assert iterative mean
assert(im == m, im .. " is not equal to " .. m)
-- test results
local valuesString = table.concat(values, ", ")
print(string.format("the calculated mean of %s: %.2f", valuesString, m))
print(string.format("the calculated iterative mean of %s: %.2f", valuesString, im))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment