Simon wrote:
> I have a quick question on the Mersenne Twister (hereinafter MT)
>
> I'm using the standard C code downloaded from the MT website
> (http://tinyurl.com/6d8t3). It's being used for a game to generate
> random levels, monsters, items and so on, and I want the game to be
> different each time I play it.
>
> The standard MT code gives me the same string of random numbers each
> time I run it. This is not surprising - computers are deterministic
> and it always starts with the same seed. The obvious way to get around
> this is to seed the MT with the current time each time the game is run.
> Although I appear to have achieved this I'm concerned that I've done
> it in a stupid / wrong way.
>
> I've made only one change to the code. In the init_by_array function
> I've changed line 79 from:
>
> init_genrand(19650218UL);
>
> to:
>
> init_genrand(time());
Well you shouldn't modify the MT code itself. Instead you should
simply call init_genrand(time(NULL)) at the start of your program and
avoid calling init_by_array() unless you have a source of real entropy
in an array somewhere.
> As I say, this seems to work fine - whenever I start up the program and
> initialise the MT I get a different string of random numbers. However,
> it would be great if someone who is familiar with MT could let me know
> whether this is a horrific hatchet job or not.
It is.

Just restrict yourself to calling init_genrand(time(NULL))
at the start of your program as I described above. That way you will
be able to use the MT source in its pristene form for other projects
and still have it synchronize with what other people expect from it.
There are more issues with using time(NULL) as a source of entropy.
The most obvious being that you can only start your program once per
second any guarantee that the sequence is different from the last time.
This usually doesn't matter, but you could see how in a distributed
system, this might be an issue (lots of machines running in parallel,
hoping to run a different instance of a simulation -- they would not be
different at all if they all started at the same time). You can find
other sources of entropy in your system (such as the value of clock()
after performing some IO, the PID, or in fact just an incrementing
counter that you read and update in a file) and add that to an array of
entropy sources (and you can include time(NULL)). Then you can use
init_by_array() to initialize MT using all those entropy sources to
reduce the probability that the sequence is the same.
--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/