Page 2 of 2

Re: Random numbers

Posted: Sat Apr 02, 2011 3:14 pm
by bartbes
Well, I guess it's partially a problem with the seed too, but I've encountered this behavior a lot.

Re: Random numbers

Posted: Sat Apr 02, 2011 5:23 pm
by bmelts
I think there's some confusion here about what the issue is. At least on the Mac, it's not that the first few numbers are uniform; it's that the first random number is basically the same for different seeds. Numbers after the first are random enough, but if you run the program several times in succession, even with different initial seeds (from os.time()) the first random number you get will generally be the same.

Observe the following Lua logs, with a delay of ten seconds between each execution:

Code: Select all

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> math.randomseed(os.time()); print(math.random()); print(math.random())
0.090166699183251
0.43171317290129
> math.randomseed(os.time()); print(math.random()); print(math.random())
0.090237136506586
0.61555326618978
> math.randomseed(os.time()); print(math.random()); print(math.random())
0.09032322656844
0.062468935764613
> math.randomseed(os.time()); print(math.random()); print(math.random())
0.090385837522515
0.11477124090994
After the first math.random(), you get reasonably random-ish numbers, but the first one is reliably similar. The problem is more noticeable when you use the integer form of math.random() (again, ten seconds between each execution):

Code: Select all

> math.randomseed(os.time()); print(math.random(100)); print(math.random(100))
10
51
> math.randomseed(os.time()); print(math.random(100)); print(math.random(100))
10
69
> math.randomseed(os.time()); print(math.random(100)); print(math.random(100))
10
87
> math.randomseed(os.time()); print(math.random(100)); print(math.random(100))
10
93
So, on platforms with crappy rand() (e.g. OS X) discarding the first couple of random numbers can be a very effective way of guaranteeing somewhat more interesting results.

Re: Random numbers

Posted: Sat Apr 02, 2011 9:43 pm
by Boolsheet
Wikipedia has a short list how some C libraries generate their numbers.
http://en.wikipedia.org/wiki/Linear_con ... common_use

I think the last column is also interesting, it shows the range of the random number.
The Windows SDK defines the following in stdlib.h:

Code: Select all

#define RAND_MAX 0x7fff
This means math.random() generates only 32767 different floating point numbers on Windows.