8protons 8protons - 1 year ago 98
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
simply just invokes
. Am I doing this incorrectly?

Answer Source

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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download