名稱空間
變體
操作

std::uniform_real_distribution

來自 cppreference.com
< cpp‎ | 數值‎ | 隨機
 
 
 
 
 
定義於標頭檔案 <random>
template< class RealType = double >
class uniform_real_distribution;
(C++11 起)

生成在區間 [a, b) 上均勻分佈的隨機浮點值 x,即根據機率密度函式分佈:

P(x|a,b) =
1
b − a

std::uniform_real_distribution 滿足 RandomNumberDistribution 的所有要求。

目錄

[編輯] 模板引數

RealType - 生成器生成的結果型別。如果這不是 floatdoublelong double 之一,則效果是未定義的。

[編輯] 成員型別

成員型別 定義
result_type(C++11) RealType
param_type (C++11) 引數集的型別,參見 RandomNumberDistribution

[編輯] 成員函式

構造新的分佈
(public member function) [編輯]
(C++11)
重置分佈的內部狀態
(public member function) [編輯]
生成
生成分佈中的下一個隨機數
(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) [編輯]
對偽隨機數分佈執行流輸入和輸出
(function template) [編輯]

[編輯] 注意

很難從這個分佈中建立覆蓋閉區間 [a, b] 的分佈。使用 std::nextafter(b, std::numeric_limits<RealType>::max()) 作為第二個引數並不總是有效,因為存在舍入誤差。

大多數現有實現都有一個錯誤,即它們可能會偶爾返回 bGCC #63176 LLVM #18767 MSVC STL #1074)。這最初只被認為發生在 RealTypefloat 且存在 LWG issue 2524 時,但後來已證明兩者都不是觸發此錯誤所必需的

[編輯] 示例

列印 10 個介於 1 和 2 之間的隨機數。

#include <iostream>
#include <random>
 
int main()
{
    std::random_device rd;  // Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
    std::uniform_real_distribution<> dis(1.0, 2.0);
    for (int n = 0; n < 10; ++n)
        // Use dis to transform the random unsigned int generated by gen into a 
        // double in [1, 2). Each call to dis(gen) generates a new random double.
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

可能的輸出

1.80829 1.15391 1.18483 1.38969 1.36094 1.0648 1.97798 1.27984 1.68261 1.57326

[編輯] 外部連結

從區間繪製隨機浮點數 — © 2022. Frédéric Goualard, Université de Nantes.