Chinaunix首页 | 论坛 | 博客
  • 博客访问: 209234
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: Java

2011-08-31 08:19:40

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.

  1. /********************************************************************
  2.   * Compilation: javac Gambler1.java
  3.   * Execution: java Gambler1 stake goal T
  4.   *
  5.   * Simulates a gambler who start with $stake and place fair $1 bets
  6.   * until she goes broker or reach $goal. Keeps track of the number of times
  7.   * she wins and the number of bets she makes. Run the experiment T times,
  8.   * average the results, and prints them out.
  9.   *
  10.   * Simple execution: % java Gambler1 500 2500 100
  11.   * Gambler wins is 18%
  12.   * Avg bets: 1036911
  13.   * ***************************************************************************/
  14. public class Gambler1 {
  15.     public static void main(String[] args) {
  16.         int stake = Integer.parseInt(args[0]); // initial stake
  17.         int goal = Integer.parseInt(args[1]); // walkaway goal
  18.         int T = Integer.parseInt(args[2]); // number of trials
  19.         
  20.         int bets = 0; // bet count
  21.         int wins = 0; // win count
  22.         //int cash = 0; // cash on hand
  23.         
  24.         // repeat experiment T times
  25.         for (int t = 0; t < T; t++) {
  26.              // do one gambler's ruin experiment
  27.             int cash = stake;
  28.             while (cash > 0 && cash < goal) {
  29.                 double r = Math.random();
  30.                 bets++;
  31.                 if (r < 0.5) {
  32.                     cash ++;
  33.                 }
  34.                 else cash--;
  35.             } // cash is either 0 (ruin) or $goal (win).
  36.             if (cash == goal) wins++;
  37.           }
  38.         
  39.         System.out.println("Gambler wins is " + 100 * wins/T + "% ");
  40.         System.out.println("Avg bets: " + bets/T);
  41.     }
  42. }

阅读(700) | 评论(0) | 转发(0) |
0

上一篇:Coupon collector

下一篇:Self-Avoiding Random Walks

给主人留下些什么吧!~~