Skip to content

Instantly share code, notes, and snippets.

@agarie
Created June 12, 2015 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agarie/16c83c28250209fbddb6 to your computer and use it in GitHub Desktop.
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.
-- Some RNGs for getting to play with Lua.
--
-- Carlos Agarie <carlos@onox.com.br>
--
-- 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