Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating uniform random numbers in Lua

Tags:

I am working on programming a Markov chain in Lua, and one element of this requires me to uniformly generate random numbers. Here is a simplified example to illustrate my question:

example = function(x)     local r = math.random(1,10)     print(r)     return x[r] end  exampleArray = {"a","b","c","d","e","f","g","h","i","j"}  print(example(exampleArray)) 

My issue is that when I re-run this program multiple times (mash F5) the exact same random number is generated resulting in the example function selecting the exact same array element. However, if I include many calls to the example function within the single program by repeating the print line at the end many times I get suitable random results.

This is not my intention as a proper Markov pseudo-random text generator should be able to run the same program with the same inputs multiple times and output different pseudo-random text every time. I have tried resetting the seed using math.randomseed(os.time()) and this makes it so the random number distribution is no longer uniform. My goal is to be able to re-run the above program and receive a randomly selected number every time.

like image 410
Starfish_Prime Avatar asked Nov 22 '13 21:11

Starfish_Prime


People also ask

How do you get uniform random numbers in Matlab?

X = rand returns a random scalar drawn from the uniform distribution in the interval (0,1). X = rand( n ) returns an n -by- n matrix of uniformly distributed random numbers.


1 Answers

You need to run math.randomseed() once before using math.random(), like this:

math.randomseed(os.time()) 

From your comment that you saw the first number is still the same. This is caused by the implementation of random generator in some platforms.

The solution is to pop some random numbers before using them for real:

math.randomseed(os.time()) math.random(); math.random(); math.random() 

Note that the standard C library random() is usually not so uniformly random, a better solution is to use a better random generator if your platform provides one.

Reference: Lua Math Library

like image 118
Yu Hao Avatar answered Oct 14 '22 13:10

Yu Hao