Computer Science 15-110, Spring 2010
Class Notes:  Monte Carlo Methods (Optional)

In class today we discussed Monte Carlo methods -- running random simulations to predict expected values.

Here is some sample code we wrote to demonstrate the technique.  It finds the odds of various sums when rolling two dice:

```import java.util.Random;
class MonteCarloDemo {

public static Random random = new Random();

public static int rollDie() {
return 1+random.nextInt(6);
}

public static double oddsOfSummingToN(int sum) {
int successes = 0;
int trials = 1000*100;
for (int trial=0; trial<trials; trial++) {
int die1 = rollDie();
int die2 = rollDie();
if (die1+die2 == sum)
successes++;
}
return 1.0*successes/trials;
}

public static void main(String[] args) {
for (int sum=0; sum<15; sum++)
System.out.println(sum + ": " + oddsOfSummingToN(sum));
}
}```

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem