本文介绍了如何在C语言中使用Mersenne Twister随机数生成库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Mersenne Twister C库之一(例如 tinymt mtwist ,或libbrahe)的种子.我找不到关于如何执行此操作的简单示例.

I want to use one of the Mersenne Twister C libraries (e.g. tinymt, mtwist, or libbrahe) in a C program. I wasn't able to find a simple minimalistic example on how to do this.

我已经通过mtwist软件包实现了这一目标,但是通过pjs的注释,我已经意识到这是错误的方法:

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.)

有人可以给我一个简单的示例,说明如何使用任何Mersenne Twister C库正确生成随机数吗?

Could anyone give me a simple example on how to properly generate random numbers with any Mersenne Twister C library?

推荐答案

以下是如何使用Mersenne Twister的mtwist实现的演示:

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;
}

编译并运行如下:

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

这篇关于如何在C语言中使用Mersenne Twister随机数生成库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 12:34