| 1 |
--[[ https://en.wikipedia.org/wiki/Normal_distribution ]] |
| 2 |
|
| 3 |
-- The Box–Muller method |
| 4 |
local function gaussian(mean, variance) |
| 5 |
local U = math.random() |
| 6 |
local V = math.random() |
| 7 |
return math.sqrt(-2.0 * variance * math.log(U)) * |
| 8 |
math.cos(2.0 * math.pi * V) + mean |
| 9 |
end |
| 10 |
|
| 11 |
local function mean(t) |
| 12 |
local sum = 0 |
| 13 |
local count = #t |
| 14 |
for i = 1, count do |
| 15 |
sum = sum + t[i] |
| 16 |
end |
| 17 |
return sum / count |
| 18 |
end |
| 19 |
|
| 20 |
local function std(t, mean) |
| 21 |
local squares = 0.0 |
| 22 |
for i = 1, #t do |
| 23 |
local deviation = math.abs(mean - t[i]) |
| 24 |
squares = squares + deviation * deviation |
| 25 |
end |
| 26 |
local variance = squares / #t |
| 27 |
return math.sqrt(variance) |
| 28 |
end |
| 29 |
|
| 30 |
local function do_the_call() |
| 31 |
local t = {} |
| 32 |
local mu = 34.0 |
| 33 |
local sigma = 10.0 |
| 34 |
|
| 35 |
for i = 1, 5 do |
| 36 |
table.insert(t, gaussian(mu, sigma)) |
| 37 |
end |
| 38 |
|
| 39 |
return string.format("Got mean: %1.5f, mu: %1.5f\nstd deviance:%1.5f, expected: %1.5f", |
| 40 |
mean(t), mu, |
| 41 |
std(t, mu), math.sqrt(sigma)) |
| 42 |
end |
| 43 |
|
| 44 |
math.randomseed(os.time()) |
| 45 |
return do_the_call |