Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

randomseed in LUA

Tags:

random

lua

I am working on a code that randomizes numbers. I put math.randomseed(os.time()) inside a loop. The code goes like this:

for i = 1, 1000 do
  math.randomseed( os.time() )
  j = math.random(i, row-one)
  u[i], u[j] = u[j], u[i]
  for k = 1, 11 do
     file:write(input2[u[i]][k], " ")
  end
  file:write"\n"
end

And when I run it several times, the whole output is always the same. Isn't the randomseed supposed to prevent repeats when re-run?

like image 514
Rachelle Avatar asked Jul 22 '13 09:07

Rachelle


2 Answers

Call math.randomseed once at the start of the program. No point calling it in a loop.

like image 131
lhf Avatar answered Nov 08 '22 08:11

lhf


Usually the first random values aren't truly random (but it never is truly random anyway, it's a pseudo-random number generator). First set a randomseed, then randomly generate it a few times. Try this code, for example:

math.randomseed( os.time() )
math.random() math.random() math.random()
for i = 1, 1000 do
  j = math.random(i, row-one)
  u[i], u[j] = u[j], u[i]
  for k = 1, 11 do
     file:write(input2[u[i]][k], " ")
  end
  file:write"\n"
end

However, you could try this from http://lua-users.org/wiki/MathLibraryTutorial:

-- improving the built-in pseudorandom generator
do
   local oldrandom = math.random
   local randomtable
   math.random = function ()
      if randomtable == nil then
         randomtable = {}
         for i = 1, 97 do
            randomtable[i] = oldrandom()
         end
      end
      local x = oldrandom()
      local i = 1 + math.floor(97*x)
      x, randomtable[i] = randomtable[i], x
      return x
   end
end
like image 39
qaisjp Avatar answered Nov 08 '22 09:11

qaisjp