算法题:不等概率0,1变成等概率

1、函数不等概率返回0和1

2、调用2次, 结果

 00 11 01 10

 

3、01和10,只是调换了顺序,概率应该是一样的

 

4、所以除了01好10,其他情况重做

 

5、代码验证

 

 原函数

    public static int sourceFunc() {
        return Math.random() > 0.7 ? 1 : 0;
    }

目标函数

    public static int targetFunc() {
        int a = sourceFunc();
        int b = sourceFunc();
        if (a == b) {
            return tmpFunc();
        }
        return a;
    }

证明等概率

     public static void main(String[] args) {
        int size = 10000;
        for (int i = 0; i < 2; i++) {
            int count = 0;
            for (int j = 0; j < size; j++) {
                if (targetFunc() == i) {
                    count++;
                }
            }
            System.out.println(i + "出现的概率:" + (count * 1d / size));
        }
    }
0出现的概率:0.4968
1出现的概率:0.5001

 

posted @ 2022-02-28 11:29  gabin  阅读(117)  评论(0编辑  收藏  举报