8protons 8protons - 15 days ago 4
C Question

Mersenne Twister (mt19937ar.c) not returning random number

I tried searching for examples on how to use the mt19937ar.c variant of Mersenne Twister but most come up in C++ and others seem to use

.

My code below:

int getRandomNum(void)
{
int i;
i = (int) genrand_int32();
return i;
}

int main(int argc, char **argv)
{
...
int m = getRandomNum();
printf("m = %d", m);
...
return 0;
}


simply spits out the same integer over and over again. Seems like a seeding issue, but every implementation that I've found of getting a random number with
mt19937
simply just invokes
genrand_int32()
. Am I doing this incorrectly?

Answer

The Mersenne Twister is not magical; it has no way of producing random results from predictable input. If you want a random sequence, you have to seed the generator by calling init_genrand() with some sort of unique value. Otherwise it'll use a fixed default seed (specifically: 5489).

An easy value to use is the current time:

init_genrand(time(NULL));

Don't call this more than once during your program, though -- otherwise, you'll restart the sequence!