boost :: random和boost:uniform_real可以使用双倍而不是浮点数吗?

Æle*_*lex 2 c++ floating-point boost uniform boost-random

如果已经讨论过,请原谅我.我有一个模板函数,它根据模板参数使用boost :: uniform_int和boost :: uniform_real,并且应该返回相同的类型:

template <typename N> N getRandom(int min, int max)
{
  timeval t;
  gettimeofday(&t,NULL);
  boost::mt19937 seed((int)t.tv_sec);
  boost::uniform_int<> dist(min, max);
  boost::variate_generator<boost::mt19937&, boost::uniform_int<> > random(seed, dist);
  return random(); 
}
//! partial specialization for real numbers
template <typename N> N getRandom(N min, N max)
{
  timeval t;
  gettimeofday(&t,NULL);
  boost::mt19937 seed( (int)t.tv_sec );
  boost::uniform_real<> dist(min,max);
  boost::variate_generator<boost::mt19937&, boost::uniform_real<> > random(seed,dist);
  return random(); 
}
Run Code Online (Sandbox Code Playgroud)

现在我用int,float和double测试了这个函数.它适用于int,它可以正常使用double,但它不适用于浮点数.就好像它将float转换为int,或者存在一些转换问题.原因我说这是因为当我这样做时:

float y = getRandom<float>(0.0,5.0);
Run Code Online (Sandbox Code Playgroud)

我总是得到一个回归.但是,就像我说的那样,它适用于双打.有什么我做错了或错过了吗?谢谢 !

Dav*_*men 7

参数0.0,5.0是双打,而不是浮点数.让他们漂浮:

float y = getRandom<float>(0.0f,5.0f);
Run Code Online (Sandbox Code Playgroud)


mrm*_*mrm 7

您甚至可以避免使用类型特征和MPL编写样板代码:

template <typename N>
N getRandom(N min, N max)
{
  typedef typename boost::mpl::if_<
    boost::is_floating_point<N>, // if we have a floating point type
    boost::uniform_real<>,       // use this, or
    boost::uniform_int<>         // else use this one
  >::type distro_type;

  timeval t;
  gettimeofday(&t,NULL);
  boost::mt19937 seed( (int)t.tv_sec );
  distro_type dist(min,max);
  boost::variate_generator<boost::mt19937&, distro_type > random(seed,dist);
  return random(); 
};
Run Code Online (Sandbox Code Playgroud)


Xeo*_*Xeo 5

不是真的解决你的问题本身,而是一个解决方案:

为什么不使用traits类来获得正确的分布类型?

template<class T>
struct distribution
{ // general case, assuming T is of integral type
  typedef boost::uniform_int<> type;
};

template<>
struct distribution<float>
{ // float case
  typedef boost::uniform_real<> type;
};

template<>
struct distribution<double>
{ // double case
  typedef boost::uniform_real<> type;
};
Run Code Online (Sandbox Code Playgroud)

使用该集,您可以拥有一个通用功能:

template <typename N> N getRandom(N min, N max)
{
  typedef typename distribution<N>::type distro_type;

  timeval t;
  gettimeofday(&t,NULL);
  boost::mt19937 seed( (int)t.tv_sec );
  distro_type dist(min,max);
  boost::variate_generator<boost::mt19937&, distro_type > random(seed,dist);
  return random(); 
};
Run Code Online (Sandbox Code Playgroud)

  • @Richard:请原谅我解决OP的问题 - 选择合适的发行版.你真的认为这值得投票吗?这个答案"没用"吗? (2认同)