Math.Random 返回范围[0,1) 等概率返回 计算机中所有的小数都是有精度的 有精度的代表是有穷尽的 可以等概率返回
等概率返回整数 转型成int类型
出现的次数都差不多 等概率
要求[0,x)范围 返回的x 的概率为x^2
连续调用两次 只有两次都落在0-x范围 返回的值才在0-x范围 所以概率为x^2
count = 0;double x = 0.17;for (int i = 0; i < testTimes; i++) {if (xToXPower2() < x) {count++;}}System.out.println((double) count / (double) testTimes);System.out.println((double) 1 - Math.pow((double) 1 - x, 2));// 是Math.max System.out.println(Math.pow(x, 2));// 返回[0,1)的一个小数// 任意的x,x属于[0,1),[0,x)范围上的数出现概率由原来的x调整成x平方public static double xToXPower2() {return Math.min(Math.random(), Math.random());}
经典面试题
f函数 可以等概率的得到随机 1-5 
在只使用f的情况下 等概率的返回随机 1-7
将f函数 改造为 0 1 发生器 1,2返回0 4,5返回1 返回1,0等比 3重新调用f函数
// lib里的,不能改!public static int f1() {return (int) (Math.random() * 5) + 1;}// 随机机制,只能用f1,// 等概率返回0和1public static int f2() {int ans = 0;do {ans = f1();} while (ans == 3);return ans < 3 ? 0 : 1;}
要等比返回随机 1-7 将上一步等比返回1,0的函数 拼成2进制 二进制7为 1 1 1 三位二进制数 可以得到0-7范围的等概率随机数
每个二进制位 调用一下函数f2 每一位都是独立调用的 所以返回的数最后也是等概率的
// 得到000 ~ 111 做到等概率 0 ~ 7等概率返回一个public static int f3() {return (f2() << 2) + (f2() << 1) + f2();}// 0 ~ 6等概率返回一个public static int f4() {int ans = 0;do {ans = f3();} while (ans == 7);return ans;}public static int g() {return f4() + 1;}
counts = new int[8];for (int i = 0; i < testTimes; i++) {int num = g();counts[num]++;}for (int i = 0; i < 8; i++) {System.out.println(i + "这个数,出现了 " + counts[i] + " 次");}

一个函数 以p概率返回0 以1-p概率返回1
调用f函数2次 返回0,0 1,1直接舍弃, 返回0,1得0 1,0得1 则 1 0 等概率 
// 你只能知道,x会以固定概率返回0和1,但是x的内容,你看不到!public static int x() {return Math.random() < 0.84 ? 0 : 1;}// 等概率返回0和1public static int y() {int ans = 0;do {ans = x();} while (ans == x());//判断第二次调用x函数是否与第一次相等 不等才结束返回return ans; //返回的1或0 必等概率}
对数器
主要利用随机函数 生成大样本 对自己写的排序函数 进行测试 防止排序函数只对特定的数值有效
使用方法
// 返回一个数组arr,arr长度[0,maxLen-1],arr中的每个值[0,maxValue-1]//构建一个随机数组 测试用public static int[] lenRandomValueRandom(int maxLen, int maxValue) {int len = (int) (Math.random() * maxLen);int[] ans = new int[len];for (int i = 0; i < len; i++) {ans[i] = (int) (Math.random() * maxValue);}return ans;}public static int[] copyArray(int[] arr) {int[] ans = new int[arr.length];for (int i = 0; i < arr.length; i++) {ans[i] = arr[i];}return ans;}
具体使用
// arr1和arr2一定等长public static boolean isSorted(int[] arr) {if (arr.length < 2) {return true;}int max = arr[0];for (int i = 1; i < arr.length; i++) {if (max > arr[i]) {return false;}max = Math.max(max, arr[i]);}return true;}public static void main(String[] args) {int maxLen = 5;int maxValue = 1000;int testTime = 10000;for (int i = 0; i < testTime; i++) {int[] arr1 = lenRandomValueRandom(maxLen, maxValue);int[] tmp = copyArray(arr1);selectionSort(arr1);if (!isSorted(arr1)) {for (int j = 0; j < tmp.length; j++) {System.out.print(tmp[j] + " ");}System.out.println();System.out.println("选择排序错了!");break;}}}
