std::normal_distribution
来自 cppreference.cn
定义于头文件 <random> |
||
template< class RealType = double > class normal_distribution; |
(自 C++11 起) | |
根据正态(或高斯)随机数分布生成随机数。 其定义为
- f(x; μ,σ) =
exp⎛1 σ√2π
⎜
⎝
⎛-1 2
⎜
⎝
⎞x-μ σ
⎟
⎠2
⎞
⎟
⎠
std::normal_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)(C++11)(C++20 中移除) |
比较两个分布对象 (函数) |
(C++11) |
对伪随机数分布执行流输入和输出 (函数模板) |
[编辑] 示例
运行此代码
#include <cmath> #include <iomanip> #include <iostream> #include <map> #include <random> #include <string> int main() { std::random_device rd{}; std::mt19937 gen{rd()}; // Values near the mean are the most likely. Standard deviation // affects the dispersion of generated values from the mean. std::normal_distribution d{5.0, 2.0}; // Draw a sample from the normal distribution and round it to an integer. auto random_int = [&d, &gen]{ return std::lround(d(gen)); }; std::map<long, unsigned> histogram{}; for (auto n{10000}; n; --n) ++histogram[random_int()]; for (const auto [k, v] : histogram) std::cout << std::setw(2) << k << ' ' << std::string(v / 200, '*') << '\n'; }
可能的输出
-1 0 1 * 2 *** 3 ***** 4 ******** 5 ********* 6 ********* 7 ****** 8 *** 9 * 10 11
[编辑] 外部链接
1. | Weisstein, Eric W. "正态分布。" 来自 MathWorld — Wolfram Web 资源。 |
2. | 正态分布 — 来自维基百科。 |