問題描述
所以,我正在嘗試創建一個隨機向量(想想幾何圖形,而不是一個可擴展的數組),每次我調用隨機向量函數時,我都會得到相同的 x 值,盡管 y 和 z 不同.
So, I'm trying to create a random vector (think geometry, not an expandable array), and every time I call my random vector function I get the same x value, though y and z are different.
int main () {
srand ( (unsigned)time(NULL));
Vector<double> a;
a.randvec();
cout << a << endl;
return 0;
}
使用函數
//random Vector
template <class T>
void Vector<T>::randvec()
{
const int min=-10, max=10;
int randx, randy, randz;
const int bucket_size = RAND_MAX/(max-min);
do randx = (rand()/bucket_size)+min;
while (randx <= min && randx >= max);
x = randx;
do randy = (rand()/bucket_size)+min;
while (randy <= min && randy >= max);
y = randy;
do randz = (rand()/bucket_size)+min;
while (randz <= min && randz >= max);
z = randz;
}
出于某種原因,randx 將始終返回 8,而其他數字似乎完全遵循(偽)隨機性.但是,如果我在 randx 之前調用定義,比如蘭迪,蘭迪將始終返回 8.
For some reason, randx will consistently return 8, whereas the other numbers seem to be following the (pseudo) randomness perfectly. However, if I put the call to define, say, randy before randx, randy will always return 8.
為什么我的第一個隨機數總是 8?是我播種不正確嗎?
Why is my first random number always 8? Am I seeding incorrectly?
推薦答案
問題是隨機數生成器的種子值非常接近 - 程序的每次運行只會改變時間的返回值() 少量 - 可能是 1 秒,甚至可能沒有!相當差的標準隨機數生成器然后使用這些相似的種子值來生成明顯相同的初始隨機數.基本上,您需要一個比 time() 更好的初始種子生成器和一個比 rand() 更好的隨機數生成器.
The issue is that the random number generator is being seeded with a values that are very close together - each run of the program only changes the return value of time() by a small amount - maybe 1 second, maybe even none! The rather poor standard random number generator then uses these similar seed values to generate apparently identical initial random numbers. Basically, you need a better initial seed generator than time() and a better random number generator than rand().
我認為實際使用的循環算法是從 Accelerated C++ 中提取的,旨在在所需范圍內產生更好的數字分布,而不是使用 mod 運算符.但它無法彌補總是(有效地)給予相同的種子.
The actual looping algorithm used is I think lifted from Accelerated C++ and is intended to produce a better spread of numbers over the required range than say using the mod operator would. But it can't compensate for always being (effectively) given the same seed.
這篇關于rand() 生成相同的數字——即使在我的主要內容中有 srand(time(NULL)) !的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!