[英]Different behavior between same call for pseudo-random number generator
我目前正在實現一個簡單的圖類,而我想要的方法之一是讓它返回一個隨機鄰居,如下所示。 但是,我發現每次運行程序時,返回nborList[r]
總是返回nborList中的相同元素。
IDType Graph::random_neighbor(const IDType source) const
{
IDVector nborList = neighbors(source);
IDType r = nrand(nborList.size());
cout << "TEST Neighbors: ";
for (IDVector::const_iterator iter = nborList.begin();
iter != nborList.end(); ++iter)
cout << *iter << " ";
cout << endl;
cout << "TEST Rand: " << r << endl;
return nborList[r];
}
int nrand(int n) // Returns number [0, n), taken from Accelerated C++
{
if (n <= 0 || n > RAND_MAX)
throw domain_error("Argument to nrand is out of range");
const int bucket_size = RAND_MAX / n;
int r;
do r = rand() / bucket_size;
while (r >= n);
return r;
}
我正在使用此Graph類的test.cpp
文件具有以下代碼:
#include <ctime>
#include <iostream>
#include "Graph.h"
using std::cout;
using std::endl;
int main()
{
srand(time(NULL));
Graph G(50);
for (int i = 1; i < 25; ++i)
if (i % 2 == 0)
G.add_edge(0, i);
G.add_edge(2, 49);
cout << "Number of nodes: " << G.size() << endl;
cout << "Number of edges: " << G.number_of_edges() << endl;
cout << "Neighbors of node 0: ";
IDVector nborList = G.neighbors(0);
for (IDVector::const_iterator iter = nborList.begin();
iter != nborList.end(); ++iter)
cout << *iter << " ";
cout << endl << endl;
cout << "Random neighbor: " << G.random_neighbor(0) << endl;
cout << "Random number: " << nrand(nborList.size()) << endl;
return 0;
}
輸出:
Number of nodes: 50
Number of edges: 13
Neighbors of node 0: 2 4 6 8 10 12 14 16 18 20 22 24
TEST Neighbors: 2 4 6 8 10 12 14 16 18 20 22 24
TEST Rand: 1
Random neighbor: 4
Random number: 9
我得到的輸出是每次,除了最后一行說Random number: 9
改變。 但是, TEST Rand: 1
始終為1,有時在我重新編譯時,它將更改為不同的數字,但是在多次運行時,它將保持相同的數字。 使用nrand(nborList.size())
調用在兩個地方看起來都是相同的,其中nborList = neighbors(source)
.. help?
謝謝!
眾所周知, rand()
很笨拙。 如果您運行一些測試並使用時間上接近的種子,那么它產生的第一個數字將始終是值接近的。 如果可以的話,我建議使用boost::random
方法。
而不是nrand函數,為什么不寫
IDType r = rand() % nborList.size();
這會給你一個數字[0, n]
,其中n是nborList.size() - 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.