Gambler's ruin. Suppose that a gambler makes a series of fair $1 bets, starting with some given initial stake. The gambler always goes broke eventualy, but when we set other limits on the game, various questions arise. Suppose that gambler decides ahead of time to walk away after reaching a certain goal. What are the chances that the gambler will win? How many bets might be needed to win or lose the game? What is the maximum amount of money that the gambler will have during the course of the game?
Gambler program is a simulation that can help answer these questions.
- /********************************************************************
-
* Compilation: javac Gambler1.java
-
* Execution: java Gambler1 stake goal T
-
*
-
* Simulates a gambler who start with $stake and place fair $1 bets
-
* until she goes broker or reach $goal. Keeps track of the number of times
-
* she wins and the number of bets she makes. Run the experiment T times,
-
* average the results, and prints them out.
-
*
-
* Simple execution: % java Gambler1 500 2500 100
-
* Gambler wins is 18%
-
* Avg bets: 1036911
-
* ***************************************************************************/
-
public class Gambler1 {
-
public static void main(String[] args) {
-
int stake = Integer.parseInt(args[0]); // initial stake
-
int goal = Integer.parseInt(args[1]); // walkaway goal
-
int T = Integer.parseInt(args[2]); // number of trials
-
-
int bets = 0; // bet count
-
int wins = 0; // win count
-
//int cash = 0; // cash on hand
-
-
// repeat experiment T times
-
for (int t = 0; t < T; t++) {
-
// do one gambler's ruin experiment
-
int cash = stake;
-
while (cash > 0 && cash < goal) {
-
double r = Math.random();
-
bets++;
-
if (r < 0.5) {
-
cash ++;
-
}
-
else cash--;
-
} // cash is either 0 (ruin) or $goal (win).
-
if (cash == goal) wins++;
-
}
-
-
System.out.println("Gambler wins is " + 100 * wins/T + "% ");
-
System.out.println("Avg bets: " + bets/T);
-
}
-
}
阅读(724) | 评论(0) | 转发(0) |