boost :: unit_test :: data :: random(-FLT_MAX,FLT_MAX)只生成+ Infinity

时间:2016-09-13 16:03:09

标签: c++ boost random

我正在使用boost::unit_test::data::random(安装了boost-1.61.0_1)我遇到了一些使用boost::unit_test::data::random(-FLT_MAX,FLT_MAX)生成随机浮点数的问题。它似乎只生成+Infinity

通过反复试验,我发现我可以分别在[-FLT_MAX,-FLT_MAX * 2^-25)[-FLT_MAX * 2^-25, FLT_MAX)中生成随机浮点数,这给了我一个可能的解决办法,但我仍然对我的内容感到好奇。我试图在[-FLT_MAX, FLT_MAX)生成花车时做错了。

#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>
#include <cfloat>

inline void in_range(float const & min, float const & x, float const & max) {
  BOOST_TEST_REQUIRE(min <= x);
  BOOST_TEST_REQUIRE(x < max);
}

static constexpr float lo{-FLT_MAX / (1024.0 * 1024.0 * 32.0)};

// this test passes
namespace bdata = boost::unit_test::data;
BOOST_DATA_TEST_CASE(low_floats, bdata::random(-FLT_MAX, lo) ^ bdata::xrange(100), x,
                     index) {
#pragma unused(index)
  in_range(-FLT_MAX, x, lo);
}
// this test passes
BOOST_DATA_TEST_CASE(high_floats, bdata::random(lo, FLT_MAX) ^ bdata::xrange(100), x,
                     index) {
#pragma unused(index)
  in_range(lo, x, FLT_MAX);
}
// this test fails
BOOST_DATA_TEST_CASE(all_floats, bdata::random(-FLT_MAX, FLT_MAX) ^ bdata::xrange(100), x,
                     index) {
#pragma unused(index)
  in_range(-FLT_MAX, x, FLT_MAX);
}

结果:

$ ./example
Running 300 test cases...
example.cpp:9: fatal error: in "all_floats": critical check x < max has failed [inf >= 3.40282347e+38]
Failure occurred in a following context:
    x = inf; index = 0; 
...
example.cpp:9: fatal error: in "all_floats": critical check x < max has failed [inf >= 3.40282347e+38]
Failure occurred in a following context:
    x = inf; index = 99; 

*** 100 failures are detected in the test module "example"

1 个答案:

答案 0 :(得分:2)

boost::unit_test::data::random使用std::uniform_real_distribution,其中包含requirement

  

需要: a ≤ bb - a ≤ numeric_limits<RealType>::max()

在您的情况下,b - a2 * FLT_MAX+Inffloat

您可以使用解决方法,也可以在double中生成并转回float