微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JAVA - 解决伯特兰的盒子悖论

如何解决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% 输出

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。