Created
June 12, 2015 00:38
-
-
Save agarie/16c83c28250209fbddb6 to your computer and use it in GitHub Desktop.
RNGs for some distributions written in Lua, mostly as a first exercise in the language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Some RNGs for getting to play with Lua. | |
-- | |
-- Carlos Agarie <[email protected]> | |
-- | |
-- Public domain. | |
-- N(mean; std^2). | |
function gauss(mean, std) | |
if std <= 0.0 then error("standard deviation must be positive!") end | |
u1 = math.random() | |
u2 = math.random() | |
r = math.sqrt(-2.0 * math.log(u1)) | |
theta = 2.0 * math.pi * u2 | |
return mean + std * r * math.sin(theta) | |
end | |
-- This distribution models the time between events in a Poisson process. | |
function exponential(mean) | |
if mean <= 0.0 then error("mean must be positive!") end | |
return -mean * math.log(math.random()) | |
end | |
-- This is a non-exponential type of distribution, one without a mean value. | |
function cauchy(median, scale) | |
if scale <= 0.0 then error("scale must be positive!") end | |
return median + scale * math.tan(math.pi * (math.random() - 0.5)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment