Search code examples
c#randommersenne-twister

Mersenne Twister random algorithm how can i seed init_genrand, random numbers are always the same C#


I'm using A C-program for MT19937, with initialization improved 2002/1/26.Coded by Takuji Nishimura and Makoto Matsumoto. taken from Codeproject link when after copying the source files and ran the random functions, i always get the same numbers. In the file instructions mentioned

Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).

How can i init the seed,

the constructor initilized it this way, which cause the random numbers always be the same:

            ulong [] init = new ulong[4];
        init[0]= 0x123;
        init[1]= 0x234;
        init[2]= 0x345;
        init[3] =0x456;
        ulong length = 4;
        init_by_array(init, length);

Solution

  • To seed a random generator you need a number that is different for each execution. Usually a number based on the system clock is used, for example:

    init_genrand((ulong)DateTime.UtcNow.Ticks);
    

    or:

    ulong[] init = { (ulong)DateTime.UtcNow.Ticks };
    ulong length = init.Length;
    init_by_array(init, length);