如何在不重新发明轮子的情况下为自定义类型生成均匀分布的随机实数
How to generate uniformly distributed random reals for custom types without reinventing the wheel?
我打算将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
}
那么,应该如何为这种自定义类型生成均匀分布的随机实数呢?有没有办法不重新发明轮子?
从这里可以看出,uniform_real_distribution
定义为:
template< class RealType = double >
class uniform_real_distribution;
RealType
在哪里:
生成器生成的结果类型。如果这不是浮点数、双精度数或长双精度数之一,则效果未定义。
似乎您的编译器明确禁止使用自定义类型作为处理(让我说)不可接受的类型的解决方案。因此,我会说你没有机会让它工作。
使用标准中定义的RealType
类型的标准随机数工具必须具有 float
、double
或 long double
作为类型模板参数,如 26.5.1.1.d 中所示:
在本子条款 26.5 中,实例化模板的效果:
<...>
d) 具有名为
RealType
的模板类型参数是未定义的,除非相应的模板参数是 CV 非限定参数并且是float
、double
或long 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 的实现没有显式调用它
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 如何在不重新发明轮子的情况下为自定义类型生成均匀分布的随机实数