Random numbers

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Random numbers

Post by bartbes »

Well, I guess it's partially a problem with the seed too, but I've encountered this behavior a lot.
User avatar
bmelts
Party member
Posts: 380
Joined: Fri Jan 30, 2009 3:16 am
Location: Wiscönsin
Contact:

Re: Random numbers

Post 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.
User avatar
Boolsheet
Inner party member
Posts: 780
Joined: Wed Dec 29, 2010 4:57 am
Location: Switzerland

Re: Random numbers

Post 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.
Shallow indentations.
Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests