Search code examples
crandommersenne-twister

How to use Mersenne Twister random number generation library in C?


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?


Solution

  • 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]$