P: Como garantir que os resultados são reproduzíveis, se o algoritmo está baseado em escolhas randômicas?
R: Os funções que geram números randômicos são determinísticos e geram sempre a mesma seqüência de números ([[http://en.wikipedia.org/wiki/Linear_congruential_generator|leia mais]]), se eles começam com o mesmo //semente// (ingl. seed). Portanto, é suficiente definir um semente fixo ou imprimir o semento usado. Um exemplo em C++
#include
#include
using namespace std;
int main(int argc, char *argv[]) {
// (1) define seed
unsigned my_favourite_seed = 314159265;
// (2) show nice message
cout << "This algorithm is running with random number generator seed " << my_favourite_seed << "." << endl;
// (3) set seed
srand48(my_favourite_seed);
// (4) show a couple of random numbers
for(unsigned i=0; i<10; i++)
cout << drand48() << endl;
}
Um exemplo em Java
import java.util.Random;
class rand {
public static void main(String args[]) {
// (1) define seed
int my_favourite_seed = 314159265;
// (2) show nice message
System.out.println("This algorithm is running with random number generator seed "+my_favourite_seed+".");
// (3) set seed
Random rng = new Random(my_favourite_seed);
// (4) show a couple of random numbers
for(int i=0; i<10; i++)
System.out.println(rng.nextDouble());
}
}