std::geometric_distribution
來自 cppreference.com
定義於標頭檔案 <random> |
||
template< class IntType = int > class geometric_distribution; |
(C++11 起) | |
生成隨機非負整數值 i,其分佈符合離散機率函式:
- P(i|p) = p · (1 − p)i
該值表示在一系列獨立的“是/否”試驗(每次成功的機率為 p)中,在恰好發生 1 次成功之前失敗的次數。
std::geometric_distribution<>(p) 完全等價於 std::negative_binomial_distribution<>(1, p)。它也是 std::exponential_distribution 的離散對應項。
std::geometric_distribution
滿足 RandomNumberDistribution。
目錄 |
[編輯] 模板引數
IntType | - | 生成器產生的結果型別。如果這不是 short、int、long、long long、unsigned short、unsigned int、unsigned long 或 unsigned long long 之一,則效果未定義。 |
[編輯] 成員型別
成員型別 | 定義 |
result_type (C++11) |
IntType |
param_type (C++11) |
引數集的型別,參見 RandomNumberDistribution。 |
[編輯] 成員函式
(C++11) |
構造新的分佈 (public member function) |
(C++11) |
重置分佈的內部狀態 (public member function) |
生成 | |
(C++11) |
生成分佈中的下一個隨機數 (public member function) |
特性 | |
(C++11) |
返回 p 分佈引數(試驗生成 true 的機率) (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) |
[編輯] 示例
std::geometric_distribution<>(0.5) 是預設值,表示獲得正面所需的拋硬幣次數。
執行此程式碼
#include <iomanip> #include <iostream> #include <map> #include <random> #include <string> int main() { std::random_device rd; std::mt19937 gen(rd()); std::geometric_distribution<> d; // same as // std::negative_binomial_distribution<> d(1, 0.5): std::map<int, int> hist; for (int n = 0; n != 10000; ++n) ++hist[d(gen)]; for (auto [x, y] : hist) { const char c = x < 10 ? x + '0' : x - 10 + 'a'; std::cout << c << ' ' << std::string(y / 100, '*') << '\n'; } }
可能的輸出
0 ************************************************* 1 ************************* 2 ************ 3 ****** 4 ** 5 * 6 7 8 9
[編輯] 外部連結
Weisstein, Eric W. "Geometric Distribution." From MathWorld — A Wolfram Web Resource. |