一、三門問題
乾貨菌之前的文章中,講到了貝葉斯概率,其中詳細討論了三門問題。這裡用計算機模擬一下效果,通過隨機的方式,來感受一下。
public class ThreeGatesExperiment {
private int N;
public ThreeGatesExperiment(int N){
if(N <= 0)
throw new IllegalArgumentException("N must be larger than 0!");
this.N = N;
}
public void run(boolean changeDoor){
int wins = 0;
for(int i = 0 ; i < N ; i ++)
if(play(changeDoor))
wins ++;
System.out.println(changeDoor ? "Change" : "Not Change");
System.out.println("winning rate: " + (double)wins/N);
}
private boolean play(boolean changeDoor){
// Door 0, 1, 2
int prizeDoor = (int)(Math.random() * 3);
int playerChoice = (int)(Math.random() * 3);
if( playerChoice == prizeDoor)
return changeDoor ? false : true;
else
return changeDoor ? true : false;
}
public static void main(String[] args) {
int N = 10000000;
ThreeGatesExperiment exp = new ThreeGatesExperiment(N);
exp.run(true);
System.out.println();
exp.run(false);
}
}
二、一定中獎嗎?
遊戲裡,寶箱獲得傳奇裝備的概率為20%,現在你打開5個寶箱,獲得傳奇裝備的概率是多少?
public class WinningPrize {
private double chance;
private int playTime;
private int N;
public WinningPrize(double chance, int playTime, int N){
if(chance < 0.0 || chance > 1.0)
throw new IllegalArgumentException("chance must be between 0 and 1!");
if(playTime <= 0 || N <= 0)
throw new IllegalArgumentException("playTime or N must be larger than 0!");
this.chance = chance;
this.playTime = playTime;
this.N = N;
}
public void run(){
int wins = 0;
for(int i = 0 ; i < N ; i ++)
if(play())
wins ++;
System.out.println("winning rate: " + (double)wins/N);
}
private boolean play(){ //模擬開寶箱
for(int i = 0 ; i < playTime ; i ++)
if(Math.random() < chance)
return true;
return false;
}
public static void main(String[] args) {
double chance = 0.2;
int playTime = 5;
int N = 1000000;
WinningPrize exp = new WinningPrize(chance, playTime, N);
exp.run();
}
}
只要寶箱中獎率不是100%,那麼抽多少次都不存在100%中獎。
隨機模擬,概率大概0.67……。
那麼數學上怎樣解釋呢?1-(0.8^5)=0.67232。 減去5次都不中的概率。
多少次能90%中獎呢?計算 1-0.8^x>0.9
那麼我們之前學的1/0.2=5,這個5是什麼鬼?是期望值。5次能夠中獎,期望是很大很大的範圍的平均,而大多數時候我們都是被平均。
賭博有風險,下注需謹慎。
閱讀更多 學點乾貨 的文章