std::generate_canonical
來自 cppreference.com
定義於標頭檔案 <random> |
||
template< class RealType, std::size_t Bits, class Generator > RealType generate_canonical( Generator& g ); |
(C++11 起) | |
生成範圍 [
0,
1)
內的隨機浮點數。
為了生成足夠的熵,generate_canonical() 將精確呼叫 g() k 次,其中 k = max(1, ⌈ b / log2 R ⌉),且
- b = std::min(Bits, std::size_t {std::numeric_limits<RealType>::digits}),
- R = g.max() - g.min() + 1.
目錄 |
[編輯] 引數
g | - | 用於獲取熵的生成器 |
[編輯] 返回值
範圍 [
0,
1)
內的浮點值。
[編輯] 異常
除 g 丟擲的異常外,無其他異常。
[編輯] 注意
一些現有實現存在一個錯誤,如果 `RealType` 是 `float`,它們偶爾可能返回 `1.0` GCC #63176 LLVM #18767 MSVC STL #1074。這是 LWG issue 2524。
[編輯] 示例
生成具有10位隨機性的隨機數:這可能只產生 k * R 個不同的值。
執行此程式碼
#include <iostream> #include <random> int main() { std::random_device rd; std::mt19937 gen(rd()); for (int n = 0; n < 10; ++n) std::cout << std::generate_canonical<double, 10>(gen) << ' '; std::cout << '\n'; }
可能的輸出
0.208143 0.824147 0.0278604 0.343183 0.0173263 0.864057 0.647037 0.539467 0.0583497 0.609219
[編輯] 另請參閱
(C++11) |
產生在給定範圍內均勻分佈的實數值 (類模板) |