int random(){
double x = ((double) rand()/(RAND_MAX)); // this i tried but only 0
return x;
}
我如何生成0或隨機播放生成0或1,而不是在
int random(){
double x = ((double) rand()/(RAND_MAX)); // this i tried but only 0
return x;
}
我如何生成0或隨機播放生成0或1,而不是在
如果你有C++11
你可以使用新的標準<random>
庫。特別是std::bernoulli_distribution分佈給出true
或false
結果(默認分別轉換爲1
和0
)。
// returns true or false
bool randomly_true(double p = 0.5)
{
thread_local static std::mt19937 mt{std::random_device{}()};
thread_local static std::bernoulli_distribution d;
return d(mt, std::bernoulli_distribution::param_type{p});
}
int main()
{
for(int i = 0; i < 30; ++i)
std::cout << randomly_true() << '\n';
}
輸出:(樣品)
0
0
0
1
0
1
1
1
0
1
如果你總是希望1
或0
整數值,而不是true
或false
布爾值,您可以通過從函數返回int
強制轉換:
// returns 1 or 0
int randomly_true(double p = 0.5)
{
thread_local static std::mt19937 mt{std::random_device{}()};
thread_local static std::bernoulli_distribution d;
return d(mt, std::bernoulli_distribution::param_type{p});
}
注意:您應該優先使用此庫,而不是rand()
,因爲rand()
不能保證質量,可能執行得很差。
通常你應該使用這個庫而不是C風格的rand(),這對於低質量的實現是臭名昭着的。 –
值得注意的是,使用Mersenne Twister和它的2.5 KiB狀態加上伯努利分佈以及它的浮點計算(當你可以取任何一點MT輸出)來決定它是tic還是tac它是可笑的。保留最低級別的LCG(或者更好,XorShift家族的任何成員)會很好。難怪他們認爲軟件不斷擴展以做同樣的事情,浪費不斷增加的硬件資源。 –
@MatteoItalia在實際的應用程序中,您將爲所有隨機需求重複使用相同的隨機數生成器,並且分發應該只提取每次調用所需的位數(它們是有狀態的)。此外,標準庫也提供LCG,如果這是您所需要的。 – Galik
如果你有'C++ 11',那麼[std :: bernoulli_distribution](http://en.cppreference.com/w/cpp/numeric/random/bernoulli_distribution)可能對你有用。 – Galik
@Galik這是一個很棒的答案。請讓它成爲答案? – sehe
就像'rand()%2'一樣簡單。 – HolyBlackCat