std:: piecewise_constant_distribution
From cppreference.net
|
定义于头文件
<random>
|
||
|
template
<
class
RealType
=
double
>
class piecewise_constant_distribution ; |
(C++11 起) | |
std::piecewise_constant_distribution
生成随机浮点数,这些数在若干子区间
[b
i
, b
i+1
)
内均匀分布,每个子区间具有各自的权重
w
i
。区间边界集合与权重集合是该分布的参数。
| w i |
| S (b i+1 - b i ) |
std::piecewise_constant_distribution
满足
RandomNumberDistribution
的所有要求。
目录 |
模板参数
| RealType | - | 生成器产生的结果类型。若该类型不是 float 、 double 或 long double 之一,则效果未定义。 |
成员类型
| 成员类型 | 定义 |
result_type
(C++11)
|
RealType |
param_type
(C++11)
|
参数集的类型,参见 RandomNumberDistribution 。 |
成员函数
|
(C++11)
|
构造新的分布
(公开成员函数) |
|
(C++11)
|
重置分布的内部状态
(公开成员函数) |
生成 |
|
|
(C++11)
|
生成分布中的下一个随机数
(公开成员函数) |
特性 |
|
|
返回分布参数
(公开成员函数) |
|
|
(C++11)
|
获取或设置分布参数对象
(公开成员函数) |
|
(C++11)
|
返回可能生成的最小值
(公开成员函数) |
|
(C++11)
|
返回可能生成的最大值
(公开成员函数) |
非成员函数
|
(C++11)
(C++11)
(removed in C++20)
|
比较两个分布对象
(函数) |
|
(C++11)
|
对伪随机数分布执行流输入和输出操作
(函数模板) |
示例
运行此代码
#include <iostream> #include <map> #include <random> #include <string> int main() { std::random_device rd; std::mt19937 gen(rd()); // 50% 的时间生成 0 到 1 之间的随机数 // 50% 的时间生成 10 到 15 之间的随机数 std::vector<double> i {0, 1, 10, 15}; std::vector<double> w {1, 0, 1}; std::piecewise_constant_distribution<> d(i.begin(), i.end(), w.begin()); std::map<int, int> hist; for (int n {}; n < 1e4; ++n) ++hist[d(gen)]; for (std::cout << std::hex << std::uppercase; auto [x, y] : hist) std::cout << x << ' ' << std::string(y / 100, '*') << '\n'; }
可能的输出:
0 ************************************************** A ********** B ********* C ********* D ********** E *********
参考文献
- C++23 标准 (ISO/IEC 14882:2024):
-
- 28.5.9.6.2 类模板 piecewise_constant_distribution [rand.dist.samp.pconst] (页码: 1421-1422)
- C++20 标准 (ISO/IEC 14882:2020):
-
- 29.6.9.6.2 类模板 piecewise_constant_distribution [rand.dist.samp.pconst] (页码: 1207-1208)
- C++17 标准 (ISO/IEC 14882:2017):
-
- 29.6.8.6.2 类模板 piecewise_constant_distribution [rand.dist.samp.pconst] (页码: 1098-1100)
- C++14 标准 (ISO/IEC 14882:2014):
-
- 26.5.8.6.2 类模板 piecewise_constant_distribution [rand.dist.samp.pconst] (页码: 962-964)
- C++11 标准 (ISO/IEC 14882:2011):
-
- 26.5.8.6.2 类模板 piecewise_constant_distribution [rand.dist.samp.pconst] (页码: 955-957)