Jump to content




Random number generation


  • You cannot reply to this topic
2 replies to this topic

#1 mrpoopy345

  • Members
  • 148 posts
  • LocationMy Computer

Posted 27 May 2015 - 09: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 by mrpoopy345, 27 May 2015 - 09:51 PM.


#2 flaghacker

  • Members
  • 655 posts

Posted 27 May 2015 - 10: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.

#3 mrpoopy345

  • Members
  • 148 posts
  • LocationMy Computer

Posted 27 May 2015 - 10: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 by mrpoopy345, 27 May 2015 - 10:26 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users