伪随机数生成器的相同调用之间的行为不同

时间:2012-01-13 05:12:47

标签: c++ random

我目前正致力于实现一个简单的图形类,我想要的方法之一就是返回一个随机邻居,如下所示。但是,我发现每次运行程序时,返回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)帮助的地方,这两个地方的通话似乎相同?

谢谢!

2 个答案:

答案 0 :(得分:1)

众所周知,{p> rand()很笨拙。如果你运行一些测试并使用接近时间的种子,它产生的第一个数字将始终接近值。如果可以的话,我建议使用像boost::random这样的东西。

答案 1 :(得分:0)

而不是nrand函数,为什么不写

IDType r = rand() % nborList.size();

这会给你一个数字[0, n],其中n是nborList.size() - 1