unsigned int random::getNext() { static unsigned int next = getRandomSeed(); // Park and Miller's minimal standard generator: // xn+1 = (a * xn + b) mod c // xn+1 = (16807 * xn) mod (2^31 - 1) next = static_cast<unsigned int>((16807 * next) % 2147483647ul); return next; }
void controller_init() { printf("Running\n"); srand (getRandomSeed()); MCManager_init(); broadcaster_init(); DSManager_init(-1); TimerManager_init(); GossipManager_init(); SnakeToQuadruped_init(1); atronApi_setLeds(255); }
int main(int argc, char *argv[]) { int i=0; double old_energy, new_energy; double delta_energy; double boltzmann_factor; double the_exponential; int monte_carlo_steps; int trial_number; double x0, y0, z0; double dx, dy, dz; double rvlen; double sum_dx, sum_dy, sum_dz; instream = stdin; while (++i < argc) { if ((argc>1) && (*argv[i] != '-')) instream = fopen(argv[i], "r"); else if (!strcmp(argv[i], "-v")) verbose = 1; else if (!strcmp(argv[i], "-T")) temperature = getDoubleParameter("temperature", argv[++i]); else if (!strcmp(argv[i], "-dim")) { box_x = getDoubleParameter("box_x", argv[++i]); box_y = getDoubleParameter("box_y", argv[++i]); box_z = getDoubleParameter("box_z", argv[++i]); } else if (!strcmp(argv[i], "-n_trials")) n_trials = getDoubleParameter("n_trials", argv[++i]); else if (!strcmp(argv[i], "-rng_seed")) rng_seed = getIntParameter("rng_seed", argv[++i]); else if (!strcmp(argv[i], "-n_steps")) n_steps = getIntParameter("n_steps", argv[++i]); else if (!strcmp(argv[i], "-randomize")) rng_seed = getRandomSeed(); else if (!strcmp(argv[i], "-perturbation_length")) perturbation_length = getDoubleParameter("perturbation_length", argv[++i]); } initializeRandomNumberGeneratorTo(rng_seed); loadConfiguration(); for (trial_number = 0; trial_number < n_trials; trial_number++) { sum_dx = 0; sum_dy = 0; sum_dz = 0; V printf("trial number %d\n", trial_number); accepted_moves = 0; // pick starting point x0 = x[number_of_molecules] = box_x * rnd(); y0 = y[number_of_molecules] = box_y * rnd(); z0 = z[number_of_molecules] = box_z * rnd(); // move it a bunch of times for(monte_carlo_steps=0; monte_carlo_steps<n_steps; monte_carlo_steps++) { dx = 2*(rnd() - .5); dy = 2*(rnd() - .5); dz = 2*(rnd() - .5); rvlen = perturbation_length / sqrt(dx*dx + dy*dy + dz*dz); dx *= rvlen; dy *= rvlen; dz *= rvlen; // try out the new position old_energy = calculateSystemEnergy(); x[number_of_molecules] += dx; y[number_of_molecules] += dy; z[number_of_molecules] += dz; adjustForBoundary(number_of_molecules); new_energy = calculateSystemEnergy(); delta_energy = new_energy - old_energy; if (delta_energy <= 0) { accepted_moves++; sum_dx += dx; sum_dy += dy; sum_dz += dz; continue; /* move accepted */ } the_exponential = 0.0 - delta_energy/temperature; if (the_exponential > -75) { boltzmann_factor = exp(the_exponential); if (boltzmann_factor > rnd()) { accepted_moves++; sum_dx += dx; sum_dy += dy; sum_dz += dz; continue; /* move accepted */ } } /* move rejected: */ x[number_of_molecules] -= dx; y[number_of_molecules] -= dy; z[number_of_molecules] -= dz; adjustForBoundary(number_of_molecules); } // look at end point, compare total_translation = sqrt(sum_dx*sum_dx + sum_dy*sum_dy + sum_dz*sum_dz); printf("%lf\n", total_translation); V printf("%lf\t%lf\t%lf\t%lf\n", sum_dx, sum_dy, sum_dz, total_translation); V printf("acceptance ratio: %lf\n", (0.0 + accepted_moves)/n_steps); } return 0; } /* end main */
/** Get a random number to seed the generator. */ static uint32 getRandomSeed(); public: /** The maximum signed integral value that can be generated by this class (similar to RAND_MAX). */ static int32 const MAX_INTEGER = 0x7FFFFFFF; /** * Constructor. * * @param seed Use this to specify your own starting random seed if necessary. * @param threadsafe Set to false if you know that this random will only be used on a single thread. This eliminates the * lock and could improve performance. */ Random(uint32 seed = getRandomSeed(), bool threadsafe = true); /** Destructor. */ virtual ~Random(); /** * Get a sequence of random bits. Subclasses can choose to override just this method and the other methods will all work * automatically. */ virtual uint32 bits(); /** Toss a fair coin. */ virtual bool coinToss(); /** Uniform random integer in the range [0, MAX_INTEGER] (both endpoints inclusive). Similar to std::rand(). */ virtual int32 integer();
double getRandomDouble(double Min, double Max) { getRandomSeed(); return ((((double)rand()) / (double)RAND_MAX) * (Max - Min)) + Min; }
int getRandom(int Min, int Max) { getRandomSeed(); return (rand() % (Max - Min +1) + Min); }
/******************************* Main... *********************************/ int main(int argc, char *argv[]) { clock_t inicial, previous, delta; double deltaTime; /*Primeiramente lemos os parametros passados:*/ interpretaParametros(argc, argv); /*Entao inicializamos nossas coisas, comecando com os graficos...*/ if (allegro_init() != 0) { printf("Incapaz de inicializar o Allegro...\n"); return 1; } set_color_depth(32); if (set_gfx_mode(GFX_AUTODETECT_WINDOWED, 1024, 768, 0, 0) != 0) { printf("Incapaz de setar o modo grafico/janela. \n"); return 2; } /* set the color palette */ set_palette(desktop_palette); srand( getRandomSeed() ); inicializaEntidades(); inicializaPassageiros(); inicializaBotes(); inicializaDesenho(); /*Qualquer codigo necessario para inicializacao de outras coisas vem aqui.*/ criaAsimov(); inicial = clock(); previous = 0; while (clock() - inicial < CLOCKS_PER_SEC*getTimeLimit() ) { delta = clock() - previous; if (delta > (double)CLOCKS_PER_SEC/(double)getFramesPerSec() ) { previous = clock(); /*Calculo da variacao de tempo (em segundo) entre o ciclo anterior e esse.*/ deltaTime = (double)delta/(double)CLOCKS_PER_SEC; /*===================================================*/ /*executa update aqui (desenho -> logica). */ /*update logico...*/ colisaoGeral(deltaTime); updateGameLogic(deltaTime); updateLogic(deltaTime); /*update grafico...*/ preparaPraDesenho(); updateDesenho(); /*Chama o update grafico de todas entidades...*/ updateScreen(); /*CHECK: >arrumar colisao pra setar a direcao certa depois de uma colisao (a normal da tangente da superficie naquele ponto) >pode ser necessario arrumar passageiro para que ele nao sete explicitamente sua direcao, mas sim que tome a cadeia de markov como "o quanto virar" para algum lado, assim poderemos ter que as entidades possam se mexer em qualquer direcao nesse incrivel mundo R2 continuo :P */ /*====================================================*/ } } /*Qualquer codigo necessario para finalizacao de outras coisas vem aqui.*/ /*Finalmente terminamos esses modulos do programa, liberando toda a memoria usada.*/ terminaDesenho(); allegro_exit(); terminaBotes(); terminaPassageiros(); terminaEntidades(); return 0; }
file.read(reinterpret_cast<char *>(&seed), sizeof seed); return seed; } return std::time(nullptr); } std::string Options::initialFile { }; std::string Options::goalFile { }; std::vector<std::string> Options::heuristics { "manhattan" }; std::string Options::searchStrategy { "uniform" }; std::string Options::astarVariant { "astar" }; bool Options::randomGoal { false }; PuzzleSize Options::generationSize { 3 }; bool Options::showMoves { false }; Options::seed_t Options::randomSeed { getRandomSeed() }; static auto getUsage(void) { po::options_description usage { "Available options" }; usage.add_options() ("help,h", "Show this help message") ("initial,i", po::value(&Options::initialFile), "Input file for the initial state") ("goal,g", po::value(&Options::goalFile), "Input file for the goal state") ("heuristics", po::value(&Options::heuristics) ->multitoken(), "Heuristics used for solving the puzzle") ("strategy", po::value(&Options::searchStrategy), "Search strategy (uniform or greedy)")
int main(int argc, char** argv) { unsigned int* __restrict address; unsigned int* __restrict memory; unsigned int i, j; unsigned int t=0; unsigned int numberOfMemoryLocation; dictionary *programInput; double startTime; double elapsedTime = 0, totalElapsedTime = 0; double initializationTime, experimentTime; programInput = ParseInput(argc, argv); ValidateParameters(); // Initialize memory manager MMMasterInitialize(0, 0, FALSE, NULL); numberOfMemoryLocation = MemorySize / sizeof(int); // Allocate memory address = MMUnitAllocate((NumberOfAccess + 8) * sizeof(unsigned int)); memory = MMUnitAllocate((numberOfMemoryLocation + 32) * sizeof(unsigned int)); // Set random seed r250_init(getRandomSeed()); // Set start time startTime = setStartTime(); printf("Initialize memory pointers with random values.."); for (i=0; i<numberOfMemoryLocation + 32; i++) { memory[i] = r250(); } // Initialize address and memory for (i=0; i<NumberOfAccess + 8; i++) { address[i] = (r250() % numberOfMemoryLocation) / 4 * 4; } printf("finished.\n"); elapsedTime = getElapsedTime(startTime) - totalElapsedTime; totalElapsedTime += elapsedTime; initializationTime = elapsedTime; // Test memory speed for read if (ReadWrite[0] == 'R' || ReadWrite[0] == 'r') { for (i=0; i<NumberOfIteration; i++) { for (j=0; j<NumberOfAccess; j++) { t += memory[address[j]]; } } } // Test memory speed for write if (ReadWrite[0] == 'W' || ReadWrite[0] == 'w') { for (i=0; i<NumberOfIteration; i++) { for (j=0; j<NumberOfAccess; j++) { memory[address[j]] += address[j]; } } } elapsedTime = getElapsedTime(startTime) - totalElapsedTime; totalElapsedTime += elapsedTime; experimentTime = elapsedTime; // So that compiler does not remove code for variables t and r if (t==0) { printf("\n"); } printf("Experiment completed.\n"); printf("Initialization time = "); printElapsedTime(stdout, FALSE, FALSE, TRUE, 2, initializationTime); printf("Experiment time = "); printElapsedTime(stdout, FALSE, FALSE, TRUE, 2, experimentTime); MMUnitFree(address, (NumberOfAccess + 8) * sizeof(unsigned int)); MMUnitFree(memory, (numberOfMemoryLocation + 32) * sizeof(unsigned int)); iniparser_freedict(programInput); return 0; }