// game2: a player gives or receives 1 unit, energy is number of units the // player has, using Metropolis acceptance // CO904, Ellak Somfai #include #include #include #define MIN(x,y) ((x)<(y) ? (x) : (y)) int main(int argc, char **argv) { int a; int i, j; double T; int mc_per_sample, n_samples; // read command line arguments if (argc == 4) { sscanf(argv[1], "%lf", &T); sscanf(argv[2], "%d", &mc_per_sample); sscanf(argv[3], "%d", &n_samples); } else { printf("Usage: game2 \n"); exit(1); } // initialise random number generator srand48(1231230); // initialise state a = 10; // loop on samples for (i = 0; i < n_samples; i++) { // loop on monte-carlo steps for (j = 0; j < mc_per_sample; j++) { int change; double e_old, e_new; double boltzmann; // change: +1 or -1 change = 2* ((int)(drand48() * 2)) - 1; if (a+change < 0) { // target is invalid: reject continue; } e_old = a; e_new = a + change; boltzmann = exp(-(e_new - e_old) / T); if (drand48() < MIN(boltzmann, 1.)) { // accept a = a + change; } } printf("%d\n", a); } return 0; }