修复c ++ 11中的种子globaly< random> [英] Fix seed globaly in c++11 <random>

查看:198
本文介绍了修复c ++ 11中的种子globaly< random>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用全局固定种子的新的 c ++ < random> 这是我的第一个玩具示例:

I'm trying to use the new c++ <random> headers with a globally fixed seed. Here is my first toy example:

#include <iostream>
#include <random>
int morerandom(const int seednum,const int nmax){
     std::mt19937 mt;
     mt.seed(seednum);
     std::uniform_int_distribution<uint32_t> uint(0,nmax);
     return(uint(mt));
}
int main(){
    const int seed=3;
    for (unsigned k=0; k<5; k++){
        std::cout << morerandom(seed,10) << std::endl;
    }
    return 0;
} 

所以问题是:如何修复 main()并从
morerandom()?获得可重现的输出?

So the question is: how can I fix the seed in the main() and get reproducible output out of morerandom()?

换句话说,我需要调用 morerandom()很多( k 会很大)但这些随机数应始终使用相同的种子绘制。我想知道是否可以/更有效地定义整个块:

In other words, I need to call morerandom() a lot (k will be large) but these random numbers should always be drawn using the same seed. I'm wondering whether it is possible/more efficient to define the whole block:

std::mt19937 mt;
mt.seed(seednum);

在主程序中,只需传递 mt morerandom()。我试过:

inside the main and just pass mt to morerandom(). I tried that:

#include <iostream>
#include <random>
int morerandom(const int nmax)
{

     std::uniform_int_distribution<uint32_t> uint(0,nmax);
     return(uint(mt));
}


int main()
{
    const int seed=3;
    std::mt19937 mt;
    mt.seed(seed);
    for (unsigned k=0; k<5; k++)
    {

        std::cout << morerandom(10) << std::endl;
    }

    return 0;
}

但编译器提示:

error: ‘mt’ was not declared in this scope return(uint(mt));


推荐答案

解决方案1 >

#include <iostream>
#include <random>

int morerandom(const int nmax, std::mt19937& mt)
//                             ^^^^^^^^^^^^^^^^
{    
     std::uniform_int_distribution<uint32_t> uint(0,nmax);
     return(uint(mt));
}    

int main()
{
    const int seed=3;
    std::mt19937 mt;
    mt.seed(seed);
    for (unsigned k=0; k<5; k++)
    {    
        std::cout << morerandom(10, mt) << std::endl;
        //                          ^^
    }

    return 0;
}

解决方案2

#include <iostream>
#include <random>

std::mt19937 mt;
// ^^^^^^^^^^^^^

int morerandom(const int nmax)
{    
     std::uniform_int_distribution<uint32_t> uint(0,nmax);
     return(uint(mt));
}    

int main()
{
    const int seed=3;
    mt.seed(seed);
    for (unsigned k=0; k<5; k++)
    {    
        std::cout << morerandom(10) << std::endl;
    }

    return 0;
}

这篇关于修复c ++ 11中的种子globaly&lt; random&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆