Random numbers
- bartbes
- Sex machine
- Posts: 4946
- Joined: Fri Aug 29, 2008 10:35 am
- Location: The Netherlands
- Contact:
Re: Random numbers
Well, I guess it's partially a problem with the seed too, but I've encountered this behavior a lot.
Re: Random numbers
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:
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):
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.
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
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
Re: Random numbers
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:
This means math.random() generates only 32767 different floating point numbers on Windows.
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
Shallow indentations.
Who is online
Users browsing this forum: No registered users and 3 guests