在CPP中在运行时选择随机数生成器

时间:2019-07-07 12:43:07

标签: c++ c++11 random mt19937

我可能正在付出不必要的努力,但是谁在乎,让我们尝试解决这个问题: 我想在代码中使用<random>中的“ random_device”生成器。但这可能在某些系统上不可用(根据规范),因此我想将mt19937作为备份(但是无论我使用什么生成器,我都希望在末尾使用相同的变量名)。现在,我可以尝试random_device看看它是否正常工作,但是那又如何呢?如果使用if语句,则生成器将在if之后消失。如果声明,则以后不能更改类型。在代码下方,不起作用。

bool random_working=true;
try
{
    random_device rd; //throws exception when not able to construct
}
catch(exception& e)
{
    cout<<"Exception: ''random_device'' not working, switching back to mt19937"<<endl;
    random_working=false;
}
if(random_working)
    random_device mc; //for _M_onte-_C_arlo
else
        mt19937 mc;

1 个答案:

答案 0 :(得分:0)

This documentation说,std::random_device在某些平台上可能是确定性来源,因此导致序列始终相同。

您可以始终保持std::mt19937seed()的时间依赖性,就像在过去的std::rand()std::srand()一样。

然后您将不得不使用一个随机分布,该分布将消耗此随机生成器并为您提供所需的随机值。

例如

#include <iostream>
#include <random>
#include <chrono>

int
main()
{
  //-- create and seed a general purpose random generator --
  using gen_t = std::mt19937;
  const auto now{std::chrono::system_clock::now().time_since_epoch()};
  const auto seed=gen_t::result_type(
    std::chrono::duration_cast<std::chrono::microseconds>(now).count());
  gen_t rndGen{seed};

  //-- create a uniform distribution of integer values in [0;255] --
  std::uniform_int_distribution<int> uniDist{0, 255};

  //-- draw a random integer value --
  const int guessThatInteger=uniDist(rndGen);

  std::cout << guessThatInteger << '\n';
  return 0;
}