//(1) 1-5的随机,不能动 1-5等概率随机,基础函数不变
public static int f1(){
return (int)(Math.random()*5) + 1;
}
//(2)根据f1() 1-5等概率,写出 0-1的等概率分布
public static int f2(){
int ans = 0;
do{
ans = f1();
} while ( ans == 3);
return ans < 3 ? 0:1;
}
//(3)根据f2() 0-1 的等概率,写出000-111 的二进制位 即为0-7 的等概率事件。
public static int f3(){
return (f2()<<2)+(f2()<<1)+(f2()<<0);
}
//(4)f3()等概率 0-7,得到 0-6 概率
public static int f4(){
int ans = 0;
do {
ans=f3();
}while (ans == 7);
return ans;
}
//测试
public static void main(String[] args) {
int countTimes=1000000;
int[] arr=new int[8];
for (int i = 0; i < countTimes; i++) {
int num=g();
arr[num]++;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(i+"这个数:出现多少次"+arr[i]);
}
}
//结果
/** * 0这个数:出现多少次0 * 1这个数:出现多少次142622 * 2这个数:出现多少次142597 * 3这个数:出现多少次142934 * 4这个数:出现多少次143030 * 5这个数:出现多少次143201 * 6这个数:出现多少次142960 * 7这个数:出现多少次142656 */
本文介绍了一种通过基本的1-5等概率随机数生成器逐步扩展到更复杂范围的随机数生成方法。从简单的1-5随机数开始,通过逻辑变换实现0-1的等概率分布,再进一步扩展到0-7的等概率随机数生成,并最终实现0-6的随机数生成,同时提供了测试代码验证随机性的均匀分布。

1826

被折叠的 条评论
为什么被折叠?



