問題描述
生成隨機數的最佳方法是什么?
What is the best way to generate random numbers?
推薦答案
當且僅當:
您不是在尋找完美的一致性"或
您沒有 C++11 支持,甚至沒有 TR1(因此您別無選擇)
那么您可能會考慮使用以下 C 風格的解決方案,其中(為了這個社區的聲譽~請參閱 rand() 被認為有害) 以刪除線字體書寫:
then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:
這是一個簡單的 C 風格的函數,它從 min
到 max
的區間生成隨機數,包括.這些數字似乎非常接近均勻分布.
Here's the simple C-style function that generates random number from the interval from min
to max
, inclusive. Those numbers seem to be very close to being uniformly distributed.
int irand(int min, int max) {
return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}
并且在使用之前不要忘記調用srand
:
int occurences[8] = {0};
srand(time(0));
for (int i = 0; i < 100000; ++i)
++occurences[irand(1,7)];
for (int i = 1; i <= 7; ++i)
printf("%d ", occurences[i]);
輸出:14253 14481 14210 14029 14289 14503 14235
還可以看看:
生成范圍內的隨機數?
在整個范圍內均勻生成隨機數
找些時間,至少觀看上述 視頻的前 11 分鐘一個>
使用
只是就像 Kerrek SB 已經指出的那樣.
use <random>
just like it was pointed out by Kerrek SB already.
這篇關于在 C++ 中生成隨機數的最佳方法是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!