Skip to content

Instantly share code, notes, and snippets.

@NanoAi
Last active March 14, 2020 18:37
Show Gist options
  • Save NanoAi/2d683ee7955fff3cf90c3c5a5d233aae to your computer and use it in GitHub Desktop.
Save NanoAi/2d683ee7955fff3cf90c3c5a5d233aae to your computer and use it in GitHub Desktop.
zscores.lua
function tableReduce(func, tbl)
local out = 0
local head = tbl[1]
local err = "May contain only numbers."
assert( type(head) == "number", err )
for _, v in next, tbl do
assert( type(v) == "number", err )
out = func(out, v)
end
return out
end
local sample = {
data = {},
index = 0,
mean = 0,
}
local function getMean()
local x = 0
x = tableReduce( function(a, b) return a + b end, sample.data )
sample.mean = ( x / #sample.data )
return sample.mean
end
local function getDeviation()
local mean = sample.mean
local x = 0
local function f(a, b)
return a + math.pow(b - mean, 2)
end
x = tableReduce( f, sample.data )
sample.deviation = x / ( #sample.data - 1 )
end
local function getZScores()
local scores = {}
for _, v in next, sample.data do
table.insert(scores, ( v - sample.mean ) / sample.deviation)
end
sample.zscores = scores
end
sample.data = {1, 1, 1, 20, 1, 2, 3, 4, 5}
getMean()
getDeviation()
getZScores()
local length = #sample.data
local txt = "Sample: {"
for k, v in next, sample.data do
txt = txt .. " " .. v
if ( k < length ) then
txt = txt .. ","
end
end
txt = txt .. " }"
print(txt)
print("Mean: ", sample.mean)
print("Deviation: ", sample.deviation)
print("Z-Scores: {")
for k, v in next, sample.zscores do
local m = tonumber(string.format("%." .. (3) .. "f", v) * 20)
print(" ", sample.data[k], " = ", v, " (x20) -> ", m, " (abs) -> ", math.abs(m) )
end
print("}")
@NanoAi
Copy link
Author

NanoAi commented Mar 14, 2020

Chart: https://jsfiddle.net/q9e8ygkf/2/ ( Made with Chart.js )
Tested with: https://www.tutorialspoint.com/execute_lua_online.php

Last Revision: Added `math.abs` for a more clear display.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment