Created
August 10, 2010 14:33
-
-
Save zach-klippenstein/517351 to your computer and use it in GitHub Desktop.
Lua script for viewing the shape of the native Lua random generator, seeded by the time.
This file contains hidden or 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
local lower = 1 | |
local upper = 20 | |
local numSamples = arg[1] or 1000 | |
local numTrials = 10 | |
local hist = {} | |
local getSeed = coroutine.create( | |
function() | |
local start | |
while true do | |
start = os.time() | |
coroutine.yield(os.time()) | |
-- Allow some time to pass so the seed value can change enough | |
while os.difftime(os.time(), start) < 1 do end | |
end | |
end | |
) | |
local seed, subject = 0, 0 | |
local sample = {} | |
function printHistogram(data, width, prefix) | |
local min, max = nil, nil | |
local adjusted | |
table.sort(data) | |
-- Calculate data bounds | |
for k, v in pairs(data) do | |
if min == nil or v < min then | |
min = v | |
end | |
if max == nil or v > max then | |
max = v | |
end | |
end | |
for k, v in pairs(data) do | |
adjusted = (v / max) * width | |
print(string.format("%s%2d|%s (%d)", prefix, k, string.rep('=', adjusted), v)) | |
end | |
end | |
for trial = 1, numTrials do | |
print(string.format("Trial #%d:", trial)) | |
err, seed = coroutine.resume(getSeed) | |
print(string.format("\tSeed=%s", tostring(seed))) | |
math.randomseed(seed) | |
-- Initialize the sample to zero-count for all numbers between lower and upper bounds | |
sample = {} | |
for i = lower, upper do sample[i] = 0 end | |
-- Generate the sample | |
for subjectNum = 1, numSamples do | |
subject = math.random(lower, upper) | |
sample[subject] = sample[subject] + 1 | |
end | |
-- Print indented histogram | |
printHistogram(sample, 20, '\t') | |
-- Save the sample | |
table.insert(hist, sample) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment