I want to use one of the Mersenne Twister C libraries (e.g. tinymt, mtwist, or libbrahe) so I can use it as a seed for rand()
in a C program. I wasn't able to find a simple minimalistic example on how to do this.
I got this far with the mtwist package, but through pjs's comments I've realized that this is the wrong way to do it:
#include <stdio.h>
#include <stdlib.h>
#include "mtwist.h"
int main() {
uint32_t random_value;
random_value = mt_lrand();
srand(random_value);
printf("mtwist random: %d; rand: %d\n", random_value, rand());
return 0;
}
(Originally I wrote that this code wouldn't compile, but thanks to Carl Norum's answer I was able to compile it afterall.)
Could anyone give me a simple example on how to properly generate random numbers with any Mersenne Twister C library?
Here's a demo of how to use the mtwist
implementation of Mersenne Twister:
#include <stdio.h>
#include <stdlib.h>
#include "mtwist.h"
int main(void) {
int i;
mt_seed();
for(i = 0; i < 10; ++i) {
printf("%f\n", mt_ldrand());
}
return EXIT_SUCCESS;
}
Compiled and run as follows:
[pjs@amber:mtwist-1.4]$ gcc run-mtwist.c mtwist.c
[pjs@amber:mtwist-1.4]$ ./a.out
0.817330
0.510354
0.035416
0.625709
0.410711
0.980872
0.965528
0.444438
0.705342
0.368748
[pjs@amber:mtwist-1.4]$
That's not a compiler error, it's a linker error. You're missing the appropriate -l
flag to link the library you're using. Your compiler invocation should look something like:
cc -o example example.c -lmtwist
I just took a quick look at the mtwist page you linked to, and it appears to be distributed just as source, not as a library. In that case, adding the appropriate implementation file to your command line should work:
cc -o example example.c mtwist.c
But you probably should look into a make
-based solution that builds a real library out of the mtwist code.