Difference between math.random() and math.randomse

2020-04-14 04:28发布

问题:

I am working on game using Corona SDK with Lua as Programming Language . While getting random number from table , I am confused to use which one of following ?

math.random()
math.randomseed()

Will any one elaborate the exact difference between them ? So I can use the best one in my case.

回答1:

If you need the same sequence when you call math.random(), then you must set math.randomseed(same number every time before calling) before calling math.random().

If you want a different sequence of random numbers, then pass math.randomseed(os.time()) before calling math.random() because os.time() will return the time in number of seconds so it will be different every time.

Please refer to following link and check example there.

https://docs.coronalabs.com/api/library/math/randomseed.html



回答2:

math.random gives you random numbers. You probably will call this many times in a program that needs random numbers.

math.randomseed determines where to start the sequence of random numbers given by math.random. You probably will call just once in a program that needs random numbers.

It seems to be a common misconception that you need to call math.randomseed before each time you call math.random. This is wrong and will defeat the randomness of math.random.



回答3:

When you execute a program that uses math.random, without setting math.randomseed, it will usually yield the same set of random numbers. This is due to the fact that math.randomseed is responsible for setting the default seed (or algorithm-generator) for the random numbers brought out by math.random.

This consistency obviously is not random. Allow me to give an example - First go to the Lua Demo Website and then insert this piece of code:

for i = 1,10 do
print(math.random())
end

Keep on consistently hitting the run button and see how the interpreter will yield the same numbers each time. However, to change the 'seed' by which the random numbers are being generated, we can just set the 'seed' to whatever the current time is (since current time never repeats)

This time go on the website and execute this code multiple times:

math.randomseed(os.time())
for i = 1,10 do
print(math.random())
end

You shall now note how you will get different numbers each time.