Random Number Generators

Random Number Generators

Many of the igraph toolbox’s functions depend on (pseudo)random numbers. These numbers can be generated with a Random Number Generator (RNG). By default, igraph will use MATLAB’s RNG. This means MATLAB function can impact the state of the RNG used by igraph and vice versa.

To get reproducible results, the RNG can be seeded using MATLAB’s rng function.

g = igraph.randgame("preference", nNodes = 50, mixingParam=0.25);
rng(1234);
expected = igraph.cluster(g, "labelPropagation");
actual = igraph.cluster(g, "labelPropagation");
disp(isequal(expected, actual));
   1

The label propagation community detection is based on randomness. The first time the algorithm is run, it requests numbers from the RNG, changing the RNG’s state so the next time cluster is called it gets new numbers. If the RNG is reset to the same state, however, the results will be the same.

rng(1234);
actual = igraph.cluster(g, "labelPropagation");
disp(isequal(expected, actual));
   1

Different RNGs

MATLAB provides different RNG algorithms (see help rng). In addition, igraph comes with its own RNGs. These can be set using igraph.rng instead of the builtin MATLAB rng. Once using an igraph RNG, the values generated in MATLAB and in igraph functions will not impact each other.

rng(1234);
fprintf("%0.2f, %0.2f\n\n", rand(1), rand(1));
0.19, 0.62

rng(1234);
x = rand(1);
igraph.cluster(g, "labelPropagation");
fprintf("%0.2f, %0.2f\n\n", x, rand(1));
0.19, 0.46

When igraph is using MATLAB’s RNG, numbers generated by igraph changes the results of random numbers generated by MATLAB. But if the RNG is changed to an igraph generator the results are decoupled.

igraph.rng(1, "pcg64");
rng(1234);
fprintf("%0.2f, %0.2f\n\n", rand(1), rand(1));
0.19, 0.62

rng(1234);
x = rand(1);
igraph.cluster(g, "labelPropagation");
fprintf("%0.2f, %0.2f\n\n", x, rand(1));
0.19, 0.62

The second random number is no longer impacted by the igraph function since igraph is using a separate RNG.

Igraph’s RNG can be seeded using the igraph.rng function. If a RNG name is not passed to igraph.rng, the current generator is reset.

MATLAB’s RNG can be used again by calling igraph.rng passing “matlab” as the generator name. If MATLAB’s RNG is currently being used by igraph, seeding igraph’s RNG with igraph.rng is equivalent to calling MATLAB’s builtin rng.

igraph.rng(1234, "matlab");
disp(randi(10, [1 5]));
     2     7     5     8     8
rng(1234);
disp(randi(10, [1 5]));
     2     7     5     8     8

Performance

On Windows, it can be slow for igraph to call MATLAB’s RNG. In many cases this shouldn’t matter but for algorithm that require a large number of random numbers, the slow down may be noticible. Neither Linux or macOS are impacted by this issue, but if reproducible results across OSes are needed, consider switching to one of igraph’s RNGs.