add pdf and cdf functions
This commit is contained in:
parent
fa0287d966
commit
4a09280be4
1 changed files with 24 additions and 0 deletions
24
util.lua
24
util.lua
|
@ -1,12 +1,14 @@
|
||||||
-- TODO: reorganize function order.
|
-- TODO: reorganize function order.
|
||||||
|
|
||||||
local assert = assert
|
local assert = assert
|
||||||
|
local exp = math.exp
|
||||||
local ipairs = ipairs
|
local ipairs = ipairs
|
||||||
local log = math.log
|
local log = math.log
|
||||||
local max = math.max
|
local max = math.max
|
||||||
local min = math.min
|
local min = math.min
|
||||||
local open = io.open
|
local open = io.open
|
||||||
local pairs = pairs
|
local pairs = pairs
|
||||||
|
local pi = math.pi
|
||||||
local random = math.random
|
local random = math.random
|
||||||
local select = select
|
local select = select
|
||||||
local sort = table.sort
|
local sort = table.sort
|
||||||
|
@ -173,6 +175,26 @@ local function exists(fn)
|
||||||
end
|
end
|
||||||
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 {
|
return {
|
||||||
signbyte=signbyte,
|
signbyte=signbyte,
|
||||||
boolean_xor=boolean_xor,
|
boolean_xor=boolean_xor,
|
||||||
|
@ -195,4 +217,6 @@ return {
|
||||||
rbool=rbool,
|
rbool=rbool,
|
||||||
argsort=argsort,
|
argsort=argsort,
|
||||||
exists=exists,
|
exists=exists,
|
||||||
|
pdf=pdf,
|
||||||
|
cdf=cdf,
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue