[英]C++ how to stop a random engine from producing negative numbers?
我有一個 function,我試圖生成 18 到 5 之間的隨機數
int randomAge() {
int random;
std::random_device rd;
static std::default_random_engine generator(rd()); //produce a static random engine
std::normal_distribution<double> distribution(18, 52); //random age between 18 and 52
random = distribution(generator);
return random;
}
但是,我收到的是負數,甚至是大於 52 的數字。我該如何解決這個問題,以便它生成 18 到 52 之間的數字?
您使用的是std::normal_distribution
,它根據正態(或高斯)隨機數分布生成隨機數。 您正在使用此構造函數:
explicit normal_distribution( RealType mean, RealType stddev = 1.0 );
你想要的是std::uniform_real_distribution
。 請參閱參考資料:
產生隨機浮點值 i,均勻分布在區間 [a, b) 上
請注意,您的引擎和發行版必須是thread_local
(或static
)並且隨機設備可以是臨時的。 否則你的結果不會均勻分布。 您還應該考慮獲得一個隨機的 integer 而不是 double 因為返回類型無論如何都是int
:
#include <random>
int randomAge() {
thread_local std::mt19937 engine{ std::random_device{}() };
thread_local std::uniform_int_distribution<int> distribution{ 18, 52 };
return distribution(engine);
}
有關的:
std::normal_distribution<T>(mean,sd)
(<-clickable link) 產生正態分布(<-clickable link),均值(中點)為mean
,標准差('spread')為sd
。
如果你想在兩個數字之間均勻分布,你需要使用std::uniform_real_distribution
(<-clickable link)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.