Module:Math: Difference between revisions

Jump to navigation Jump to search
Content added Content deleted
en>Primefac
(fix typo)
en>Primefac
(implementing pseudo-TPER to add "median" - see Special:PermaLink/861908321#Module:Average)
Line 219: Line 219:
if max_value then
if max_value then
return max_value
return max_value
end
end

--[[
median

Find the median of set of numbers

Usage:
{{#invoke:Math | median | number1 | number2 | ...}}
OR
{{#invoke:Math | median }}
]]

function wrap.median(args)
return p._median(args)
end

function p._median(args)
local vals = {}
local count = 0
for k,v in pairs(args) do
if v == string.match(v,'(%d+)') then
table.insert(vals,v)
count = count+1
end
end
table.sort(vals,function(a,b) return tonumber(a) < tonumber(b) end) -- force number sort
if count/2 == math.ceil(count/2) then
return (vals[count/2] + vals[count/2+1])/2
else
return vals[math.ceil(count/2)];
end
end
end
end