add pdf and cdf functions

This commit is contained in:
Connor Olding 2018-06-11 08:11:23 +02:00
parent fa0287d966
commit 4a09280be4

View File

@ -1,12 +1,14 @@
-- TODO: reorganize function order.
local assert = assert
local exp = math.exp
local ipairs = ipairs
local log = math.log
local max = math.max
local min = math.min
local open = io.open
local pairs = pairs
local pi = math.pi
local random = math.random
local select = select
local sort = table.sort
@ -173,6 +175,26 @@ local function exists(fn)
end
end
local function pdf(x, mean, std)
-- probability density function for a normal distribution.
mean = mean or 0
std = std or 1
if mean == 0 and std == 1 then
return 0.39894228040143 * exp(x * x * -0.5)
end
local var = std * std
return 1 / sqrt(2 * pi * var) * exp((x - mean) * (x - mean) / (-2 * var))
end
local function cdf(x)
-- a very rough approximation of the
-- cumulative distribution function for a normal distribution.
-- absolute error peaks at plus-or-minus 1.654.
-- i don't remember where this is from.
local sign = x >= 0 and 1 or -1
return 0.5 * (1 + sign * sqrt(1 - exp(-2 / pi * x * x)))
end
return {
signbyte=signbyte,
boolean_xor=boolean_xor,
@ -195,4 +217,6 @@ return {
rbool=rbool,
argsort=argsort,
exists=exists,
pdf=pdf,
cdf=cdf,
}