题目
请利用已有函数f()编写等概率0,1发生器
f()是不等概率的0,1发生器
public class Random01 {
/**
* 已有函数,不等概率的0,1发生器
* 题目提供
*
* @return
*/
public static int f(){
return Math.random()>0.8? 0:1;
}
}
解题思路
- 执行两次
- 00的概率 0.8 * 0.8
- 11的概率 0.2 * 0.2
- 01的概率 0.8 * 0.2
- 10的概率 0.2 * 0.8
- 由此得出,01和10是等概率的
- 此题得解
/**
* 请利用已有函数f()编写等概率0,1发生器
*/
public class Random01 {
/**
* 已有函数,不等概率的0,1发生器
* 题目提供
*
* @return
*/
public static int f(){
return Math.random()>0.8? 0:1;
}
/******************答题部分*********************/
/**
* 执行两次
* 00的概率 0.8 * 0.8
* 11的概率 0.2 * 0.2
* 01的概率 0.8 * 0.2
* 10的概率 0.2 * 0.8
* 由此得出,01和10是等概率的
* 此题得解
* @return
*/
public static int f1(){
int a;
do {
a = f();
} while (a==f());
return a;
}
public static void main(String[] args) {
int size = 2;
int[] count = new int[size];
for (int i = 1; i < 10_000_000L; i++) {
count[f1()]++;
}
for (int i = 0; i < size; i++) {
System.out.println("出现" + i + "的次数为:" + count[i]);
}
}
}
测试结果
出现0的次数为:4996271
出现1的次数为:5003728