首页 > 解决方案 > JAVA - 解决伯特兰盒子悖论

问题描述

我正在尝试创建一个代码块来模拟 Bertrand 盒子悖论的 100000 次迭代。这是问题(取自维基百科):

有三个盒子:

a box containing two gold coins,
a box containing two silver coins,
a box containing one gold coin and one silver coin.

“悖论”在于,在随机选择一个盒子并随机取出一枚硬币(如果碰巧是金币)之后,从同一个盒子中抽出的下一枚硬币也可能是金币。

根据贝叶斯定理,答案应该是 66%。但我的代码在所选框中返回第二枚金币的几率为 58%。

这是代码:

        double probabilityGold = 0;
        double probabilitySilver = 0;

        Random random = new Random();

        String[][] boxesOfCoins = { { "S", "G" }, { "S", "S" }, { "G", "G" } };

        int matches = 100000;
        while( matches > 0 ) {
            
            int drawBox = random.nextInt( 3 );
            int drawCoin = random.nextInt( 2 );
            String coinDrawn = boxesOfCoins[ drawBox ][ drawCoin ];

            // to ensure that the first coin picked is a gold coin
            while( coinDrawn.equals( "S" ) ) {
                drawBox = random.nextInt( 3 );
                drawCoin = random.nextInt( 2 );
                coinDrawn = boxesOfCoins[ random.nextInt( 3 ) ][ random.nextInt( 2 ) ];
            }

            if( drawCoin == 1 ) {
                String secondCoin = boxesOfCoins[ drawBox ][ 0 ];
                if( secondCoin.equals( "G" ) ) {
                    probabilityGold++;
                } else {
                    probabilitySilver++;
                }
            } else {
                String secondCoin = boxesOfCoins[ drawBox ][ 1 ];
                if( secondCoin.equals( "G" ) ) {
                    probabilityGold++;
                } else {
                    probabilitySilver++;
                }
            }

            matches--;
        }
        
        System.out.println( probabilityGold/100000 );
        System.out.println( probabilitySilver/100000 );

我的错误可能是实现了一个寻找硬币的游戏,但是,我无法解决它。我该怎么做才能获得所需的 66% 输出?

标签: javastatistics

解决方案


推荐阅读