Created
October 24, 2013 04:13
-
-
Save jsharf/7131266 to your computer and use it in GitHub Desktop.
Monte Carlo Simulation of http://mathoverflow.net/questions/9037/how-is-it-that-you-can-guess-if-one-of-a-pair-of-random-numbers-is-larger-with
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <math.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
int main(int argc, char *argv[]) | |
{ | |
srand(time(0)); | |
// successes is the number of times the "smart" | |
// method correctly guesses >/<. dumb_successes is the | |
// number of times the trivial 50-50 method is correct | |
int i, successes = 0, dumb_successes = 0, total_trials=100000; | |
for (i=0; i<total_trials; i++) | |
{ | |
// generate first and second random numbers | |
int first = rand(), second = rand(); | |
// generate third random number | |
int x = rand(); | |
// if third random number > first random number | |
if (x > first) | |
{ | |
// then our guess is that the second number is also greater | |
if (second > first) | |
{ | |
successes++; | |
} | |
} | |
// if third random number < first random number | |
if (x < first) | |
{ | |
// then our guess is that hte second number is also less | |
if (second < first) | |
{ | |
successes++; | |
} | |
} | |
// now for the dumb method: arbitrarily chose greater than or less than | |
// To chose this, I just use x%2. odd means guess "greater", even means | |
// guess "less than" | |
// greater than | |
if (x%2 == 1) | |
{ | |
// if correct, increment dumb successes | |
if (second > first) | |
{ | |
dumb_successes++; | |
} | |
} | |
// less than | |
if (x%2 == 0) | |
{ | |
if (second < first) | |
{ | |
dumb_successes++; | |
} | |
} | |
} | |
printf("Smart method: %f\n", ((double) successes)/total_trials); | |
printf("Dumb method: %f\n", ((double) dumb_successes)/total_trials); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment