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

泪湿孤枕 提交于 2019-12-06 11:17:20

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!