[英]What is the range limit for uniform real distributions?
我想在double
浮點數范圍的數字限制內創建一個隨機數。 我認為這很容易:
#include <random>
#include <cassert>
#include <math.h>
int main()
{
double a = std::numeric_limits<double>::lowest();
double b = std::numeric_limits<double>::max();
std::default_random_engine engine;
std::uniform_real_distribution<double> dist(a, b);
assert(std::isfinite(dist(engine))); // this triggers!
return 0;
}
斷言對於clang 3.8.0
和gcc 5.4.0
均失敗,因為顯然dist(engine)
的結果是inf
。 我在構造dist
時嘗試使用nextafter(a,0)
和nextafter(b,0)
代替a
和b
,但是得到了相同的結果。
根據std::uniform_real_distribution
,方法min
和max
應該提供將返回的數字范圍,但是顯然不是這樣:
std::cout << dist.min() << ", " << dist.max() << std::endl;
輸出為:
-1.79769e + 308,1.79769e + 308
並且,正如預期的那樣,以下斷言觸發,證明了這一矛盾:
const auto rand = dist(engine);
assert(rand <= dist.max() && rand >= dist.min());
同樣,兩個編譯器的結果相同。 根據min
和max
的定義,上述斷言不應觸發。 這是怎么回事?
您的代碼表現出不確定的行為,因為它破壞了以下條件:
N4140§26.5.8.2.2 [rand.dist.uni.real]
explicit uniform_real_distribution(RealType a = 0.0, RealType b = 1.0);
要求:
a ≤ b
和b − a ≤ numeric_limits<RealType>::max()
。
要回答您的問題,因此uniform_real_distribution
的范圍限制為[a/2,b/2]
,其中a
和b
是您的浮點類型的lowest
和max
數值限制值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.