經典問題:現有A,B,C三個盒子,其中一個內有獎品。某人選定一個后,系統從剩余的兩個中排除掉一個未中獎的盒子。此時更換選擇還是堅持原來的選擇,哪個會增大獲獎概率?
解答:不換時中獎概率是1/3,換了之后中獎概率時2/3。初始時,ABC每個中獎的概率都是1/3,假如你選了A,那么B+C的中獎概率是2/3。假設此時系統排除了不中獎的C,則A中獎概率還是1/3,這時候用B替換B+C,則現在B中獎的概率變為2/3。所以改變選擇提高中獎概率。
代碼實現:
public class Main{ public static void main(String[] args){ int count=200;//實驗次數 System.out.println("不換測試:"); test(count,false); System.out.println("更換測試:"); test(count,true); } private static void test(int count, boolean index) { int counts=0;//中獎次數 for(int i=1;i<=count;i++){ int price=(int)(Math.random()*3)+1;//中獎號碼為0/1/2中的一個 int start=(int)(Math.random()*3)+1;//最初選定號碼 int end=0;//最終選定號碼 int delete=0;//選定刪除的選項 if(start==price){//開始時選中了 boolean b=(int)Math.random()*2==1;//b為true或false switch(price){ case 1:{ delete=b?2:3; break; } case 2:{ delete=b?1:3; break; } case 3:{ delete=b?1:2; break; } } } else{//開始時未選中中獎號碼 delete=1+2+3-price-start;//排除的選項既不中獎,也不是最初的選擇 } if(index){//更換號碼 end=1+2+3-start-delete; } else//不更換號碼 end=start; System.out.format("第%d次選 中獎號為%d 初始選了%d 排除了%d 最終選了%d ",i,price,start,delete,end); if(end==price){ counts++; System.out.println("中獎了"); } else{ System.out.println("未中獎"); } } System.out.format("進行%d次測試,中獎%d次", count, counts); System.out.println(); } }
結果展示:
各實驗100次,最終更換選擇的中獎概率接近2/3(65/100),不更換的中獎概率約為1/3(32/100)