boost::random和boost:uniform_real适用于doubles,而不适用于float

boost::random and boost:uniform_real works with doubles not with floats?

本文关键字:boost 适用于 不适用 float doubles real random uniform      更新时间:2023-10-16

如果已经讨论过了,请原谅。我有一个模板函数,它根据模板参数使用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(); 
}

现在我已经用int、float和doubles测试了这个函数。它对int很好,对double也很好,但对float不起作用。这就好像它要么将浮点转换为int,要么存在某种类型转换问题。我之所以这么说是因为当我这样做的时候:

float y = getRandom<float>(0.0,5.0);

我总是得到一个int。然而,正如我所说,它适用于双打。是我做错了什么还是遗漏了什么?非常感谢。

参数0.0,5.0是双精度的,而不是浮点值。使其浮动:

float y = getRandom<float>(0.0f,5.0f);

您甚至可以避免编写具有类型特征和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(); 
};

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

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

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

有了这套,你就可以有一个通用功能:

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(); 
};
相关文章: