This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
mrpoopy345's profile picture

Random number generation

Started by mrpoopy345, 27 May 2015 - 08:51 PM
mrpoopy345 #1
Posted 27 May 2015 - 10:51 PM
In vanilla lua, before generating a random number you have to use math.randomseed(os.time()) In order to stop from generating the same random number over and over again. The main problem with this is that if you are generating 50 random numbers in a row in say a for loop, they will all be the same because in the time it takes to generate all of them os.time() does not change. However, in computercraft, if you do something like

for i=1, 50 do
print(math.random(1,2))
end
All the random number will be different, which is not the case in regular lua, as I explained. How does computercraft achieve this? I looked through the source and could not find any redefinition of math.random (At least in the lua section) yet it seems to work differently. How is this achieved, and how can I do it in vanilla lua?


P.S. We have a stackexchange tag now :D/>
Edited on 27 May 2015 - 08:51 PM
flaghacker #2
Posted 27 May 2015 - 11:11 PM
If you generate multiple random numbers after each other without resetting the seed, all those numbers will be diffrent.

You only have to set the seed once to generate a random sequence of numbers, even in "vanilla" Lua.
mrpoopy345 #3
Posted 27 May 2015 - 11:25 PM
Then there must be something wrong with my lua installation or code, because:

numofheads = 0
k= 1000
for i = 1, k do
	math.randomseed(os.time())
	l = math.random(1, 2)
    if l == 1 then
    	numofheads = numofheads+1
    end
end
print(numofheads)
Always returns 0 or 1000. Is there a reason for this?

EDIT: Ah, I see the problem. I have to set the randomseed before the loop. Thanks for the clarification.
Edited on 27 May 2015 - 09:26 PM