std::normal_distribution
來自 cppreference.com
定義於標頭檔案 <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) |
構造新的分佈 (public member function) |
(C++11) |
重置分佈的內部狀態 (public member function) |
生成 | |
(C++11) |
生成分佈中的下一個隨機數 (public member function) |
特性 | |
(C++11) |
返回分佈引數 (public member function) |
(C++11) |
獲取或設定分佈引數物件 (public member function) |
(C++11) |
返回可能生成的最小值 (public member function) |
(C++11) |
返回可能生成的最大值 (public member function) |
[編輯] 非成員函式
(C++11起)(C++11起)(C++20中移除) |
比較兩個分佈物件 (function) |
(C++11) |
對偽隨機數分佈執行流輸入和輸出 (function template) |
[編輯] 示例
執行此程式碼
#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. "Normal Distribution." From MathWorld — A Wolfram Web Resource. |
2. | 正態分佈 — From Wikipedia。 |