Boost Graph Library, Erdos Renyi Generator. Graphs always have same number of edges

≡放荡痞女 提交于 2020-05-16 02:42:07

问题


I'm trying to generate Erdos-Renyi graphs using boost graph library.

In the code below, which is taken from The Boost 1.72 documentation

the networks always have the same number of edges (they should not, for particular p values). I have tried using different random seeds to no avail.

Thanks for any help.

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/random/linear_congruential.hpp>
#include <iostream>

using namespace std;

typedef boost::adjacency_list<> Graph;
typedef boost::sorted_erdos_renyi_iterator<boost::minstd_rand, Graph> ERGen;

int main()
{
  boost::minstd_rand gen;
  // Create graph with 100 nodes and edges with probability 0.05
  Graph g(ERGen(gen, 100, 0.05), ERGen(), 100);
  cout << num_edges(g)<<endl;
  return 0;
}


回答1:


You should use a randomized seed:

boost::minstd_rand gen(std::random_device{}());

The nature of PRNG is that they generate deterministic output from a given state.

Live On Coliru

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/random/linear_congruential.hpp>
#include <iostream>
#include <random>

using namespace std;

typedef boost::adjacency_list<> Graph;
typedef boost::sorted_erdos_renyi_iterator<boost::minstd_rand, Graph> ERGen;

int main() {
    boost::minstd_rand gen(std::random_device{}());
    // Create graph with 100 nodes and edges with probability 0.05
    Graph g(ERGen(gen, 100, 0.05), ERGen(), 100);
    cout << num_edges(g) << endl;
}

Prints, e.g.

515
491
518
511


来源:https://stackoverflow.com/questions/61294969/boost-graph-library-erdos-renyi-generator-graphs-always-have-same-number-of-ed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!