指定范围随机数
例如基于【1-5】随机到【1-7】
public class Code2_RandToRand {// 返回[1,5] 随机整数int f1() {// [0,1) 随机doubledouble random = Math.random();// [0,6] 随机整数return (int) (random * 5) + 1;}// 从[1,5]随机数转换为0和1的随机数int f2() {int i;do {i = f1();if (i < 3) { //小于3 转为0return 0;}if (i > 3) { //大于3 转为1return 1;}} while (i == 3); //等于3 重新随机return i;}// 从0和1的随机数转为[0-6]// 需要3个bit 000->111 当为7时重新随机int f3() {int i;do {i = (f2() << 2) + (f2() << 1) + f2();if (i < 7) {return i;}} while (i == 7);return i;}// 将[0-6]转为[1-7]int f4() {return f3() + 1;}public static void main(String[] args) {Code2_RandToRand rangeRandom = new Code2_RandToRand();int[] arr = new int[8];for (int i = 0; i < 700000; i++) {arr[rangeRandom.f4()]++;}System.out.println(Arrays.toString(arr)); //0位置出现0次,1到7位置上出现次数大致相同}
}
等概率随机:
基于一个随机函数,将不等概率返回值,调整为等概率返回值
public class Code3_SamePossibleRand {/*** 有个函数以70%概率返回0,30%概率返回1* @return 返回值*/public static int x() {return Math.random() < 0.7 ? 0 : 1;}/*** 基于x函数实现,等概率返回0和1* @return 返回值*/public static int y(){int a=0;do{a=x();}while (a==x());return a;}public static void main(String[] args) {int[] arr=new int[2];for (int i=0;i<1000000;i++){arr[y()]++;}System.out.println(Arrays.toString(arr));}
}