c++ - C++ 11 mersenne_twister_engine 类的问题

标签 c++ c++11 random mersenne-twister

我一直在尝试使用 c++ 11 mersenne_twister_engine 类 ( http://www.cplusplus.com/reference/random/mersenne_twister_engine/ ) 生成区间 [0,1] 中的数字,但是我不断地在每个数字上得到 0。

这是我的代码片段

unsigned seed1 = std::chrono::system_clock::now().time_since_epoch().count();   

std::mt19937 generator(seed1); 
for (int i=0; i < WIDTH * HEIGHT; i++) //GENERATES THE MATRIX OF CONNECTIVITY
{

    double random = generator()/generator.max();
    if ( random  > VERT_CONNECTIVITY )
    vert_con[i] = 0;
    else vert_con[i] = 1;


}

generator() 和 generator.max() 似乎在工作......它只是随机的,给我 0!

谢谢!

最佳答案

使用 random header 中提供的发行版之一可能更有意义。正如 Cubbi 指出的那样 std::bernoulli_distribution看起来很适合您的问题。它会根据你传入的分布参数生成truefalse:

#include <iostream>
#include <random>
#include <vector>
#include <algorithm>

const int WIDTH = 5 ;
const int HEIGHT = 5 ;
const double VERT_CONNECTIVITY = 0.25 ;

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());

    // give "true" 1/4 of the time
    // give "false" 3/4 of the time
    std::bernoulli_distribution d(VERT_CONNECTIVITY);

    std::vector<int> vert_con( WIDTH * HEIGHT ) ;

    std::generate( std::begin(vert_con), std::end( vert_con ), [&] () { return d(gen) ; } ) ;

    for (int i=0; i < WIDTH * HEIGHT; i++) 
    {
        std::cout << vert_con[i] << " " ;
    }
    std::cout << std::endl ;

    return 0 ;
}

关于c++ - C++ 11 mersenne_twister_engine 类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20527043/

相关文章:

c++ - C++11 委托(delegate)构造函数功能的实现导致了几个警告

c++ - 获取指向 boost::any 内容的 void* 指针

c++ - 具有可变参数模板的函数

android - 如何生成一定范围内的随机数?

python - 这是什么声音?

c++ - CMake在编译使用OpenCV的项目时遇到问题

c++ - 有没有正确的方法在 C++ 中通过引用返回一个新的对象实例?

c++ - 自动转换模板<T>到模板<const T>

c++ - 仅在 Linux 上出现奇怪的 C++ 未知错误

ASP.net 列表随机排序