【发布时间】:2017-01-21 09:09:29
【问题描述】:
我打算将std::uniform_real_distribution 与一些非内置的类浮点类型一起使用,例如half_float::half 或 boost::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
}
那么,应该如何为此类自定义类型生成均匀分布的随机实数?有没有办法不用重新发明轮子?
【问题讨论】:
-
如何定义一个接受 1 到 n 个浮点数并返回您最喜欢的浮点类型的函数?然后将随机浮点数作为输入,也许作为默认参数。
-
@lorro 你的意思是一个函数将浮点类型从内置类型转换为我需要的类型吗?但这不会使分布保持一致。
-
我的意思是数学意义上的“函数”:自定义浮点数和 N 个标准浮点数之间的一对一映射(反之亦然,如果你的浮点数小于标准浮点数) .用整数更容易解释:伪代码:
int64_t getint64(int32_t a, int32_t b) { return int64_t(a) << 32 + b; }。可以为所有类型创建这样的函数(也许通过忽略最重要的位中的一些位)。 -
@lorro 为浮点数定义这样一个函数的棘手部分是确保对于均匀分布在
[a,b) intersected with the set of values of input type上的 N 个参数,它会给出均匀分布在[a,b) intersected with the set of values of output types上的结果。
标签: c++ random floating-point