如何在不重新发明轮子的情况下为自定义类型生成均匀分布的随机实数

How to generate uniformly distributed random reals for custom types without reinventing the wheel?

本文关键字:类型 实数 随机 分布 自定义 情况下 新发明      更新时间:2023-10-16

我打算将std::uniform_real_distribution与一些非内置的浮点类类型一起使用,例如 half_float::halfboost::multiprecision::float128 .但我得到的是

/

opt/gcc-5.2/include/c++/5.2.0/bits/random.h:1868:7:错误:静态断言失败:模板参数不是浮点类型

来自 G++ 5.2。这是示例程序(使用 g++ -std=c++11 -fext-numeric-literals test.cpp -o test 编译):

#include <random>
#include <boost/multiprecision/float128.hpp>
#include <half.hpp>
template<typename Float>
void test()
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<Float> rnd(Float(1),Float(10));
}
int main()
{
    test<float>();
    test<double>();
    test<long double>();
    test<boost::multiprecision::float128>(); // doesn't compile
    test<half_float::half>(); // doesn't compile
}

那么,应该如何为这种自定义类型生成均匀分布的随机实数呢?有没有办法不重新发明轮子?

从这里可以看出,uniform_real_distribution定义为:

template< class RealType = double >
class uniform_real_distribution;

RealType在哪里:

生成器生成的结果类型。如果这不是浮点数、双精度数或长双精度数之一,则效果未定义。

似乎您的编译器明确禁止使用自定义类型作为处理(让我说)不可接受的类型的解决方案。因此,我会说你没有机会让它工作。

使用标准中定义的RealType类型的标准随机数工具必须具有 floatdoublelong double 作为类型模板参数,如 26.5.1.1.d 中所示:

在本子条款 26.5 中,实例化模板的效果:

<...>

d) 具有名为 RealType 的模板类型参数是未定义的,除非相应的模板参数是 CV 非限定参数并且是 floatdoublelong double 之一。

一种解决方案是将std::uniform_real_distribution替换为 boost::random::uniform_real_distribution .后者确实接受非内置浮点类型。下面是一个具有合理类型*的示例:

#include <random>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/multiprecision/float128.hpp>
template<typename Float>
void test()
{
    std::random_device rd;
    std::mt19937 mt(rd());
    boost::random::uniform_real_distribution<Float> rnd(Float(1),Float(10));
}
int main()
{
    test<float>();
    test<double>();
    test<long double>();
    test<boost::multiprecision::float128>();
}

* half_float::half不起作用,因为它乘以常量会导致float,而half_float::half(float)构造函数是显式的,并且 Boost 的实现没有显式调用它