Java code Monte Carlo method to find the probability of the box taking the ball

Monte Carlo method to find the probability of the box taking the ball

topic

Three boxes contain white balls, white balls, white balls, black balls, black balls, and black balls.
Question: When a ball taken out is black, the probability that another ball taken out is also black.

Java code implementation

public class Main {
    public static void main(String[] args) {
        Random random = new Random();
        //模拟三个盒子 0是白色, 1 是黑色
        Box[] boxes = new Box[]{
                new Box(0, 0),
                new Box(0, 1),
                new Box(1, 1)
                //当拿到一个黑色时,再取出一个的概率是多少?

        };
        //取第一个球,是黑色时的次数
        double countBlackOneCount = 0;
        //另一个个球,仍然是黑色的次数
        double countBlackTwoCount = 0;
        //总共取球次数
        int count = 1000000;
        for(int i =0;i<count;i++) {
            int selectedBox = random.nextInt(3);
            int selectedBall = random.nextInt(2);
            if(boxes[selectedBox].getBall(selectedBall) == 0){

                //取得一个黑球
            }else if(boxes[selectedBox].getBall(selectedBall) == 1){
                countBlackOneCount++;
                int otherBall;
                if(selectedBall == 0){
                    otherBall = 1;
                }else{
                    otherBall = 0;
                }
                if(boxes[selectedBox].getBall(otherBall) == 1){
                    countBlackTwoCount++;
                }
            }
        }
        System.out.println("总取球次数: " + count);
        System.out.println("取出第一个球是黑球的次数: " + countBlackOneCount);
        System.out.println("取出黑球后取另一个球仍然是黑球的次数: " + countBlackTwoCount);
        System.out.println("取出第二个球是黑球的次数/取出第一个球是黑球的次数: " + (countBlackTwoCount / countBlackOneCount) + "%");
    }

    static class Box{
        int ball0;
        int ball1;
        public Box(int ball0, int ball1){
            this.ball0 = ball0;
            this.ball1 = ball1;
        }
        public int getBall(int id){
            if(id == 0){
                return ball0;
            }else if(id == 1){
                return ball1;
            }else{
                throw new RuntimeException("Unsupported ball id: " + id);
            }
        }
    }
}

Output

Total number of ball fetches: 1000000 Number of times the
first ball was taken out as a black ball: 5000 14.0 Number of times that
the black ball was taken out and another ball was still a black ball: 333503.0 Number of times the
second ball was taken out as a black ball/The first ball was taken out The number of times it is a black ball: 0.666987324354918%

Guess you like

Origin blog.csdn.net/killingbow/article/details/90510964