Math.random()
关于Java中的Math.random()函数大家应该都不陌生,调用后,会等概率的返回[0,1)之间double类型的小数。
为什么会说是等概率的数呢?来,让我们测试一下
int testTime = 1000000;
int count = 0;
for (int i = 0; i < testTime; i++) {
if (Math.random() < 0.25){
count++;
}
}
System.out.println((double)count / (double)testTime);
一共测试testTime次,如果< 0.25则count++,最后再用count次数 / testTime,就是Math.random中 < 0.25的次数。
那么Math.random * K,是否也是等概率的返回。
int testTime = 1000000;
int[] counts = new int[8];
for (int i = 0; i < testTime; i++) {
int index = (int)( Math.random() * 8);
counts[index]++;
}
for (int j = 0; j < counts.length; j++) {
System.out.println(counts[j]);
}
假设K = 8,经过测试发现,Math.random * 8,会等概率的返回(0,8]之间的数。
经过之前的测试发现,每次Math.random()函数,返回(0,X]之间的数的概率,都是X
那么,该如何让 (0,X] 之间返回的数,是之前的平方呢?
int testTime = 1000000;
int count = 0;
double x = 0.3;
//(0,x]
for (int i = 0; i < testTime; i++) {
if (Math.max(Math.random(),Math.random())< x){
count ++;
}
}
System.out.println((double) count / (double) testTime);
System.out.println(Math.pow(x,2));
调用一次Math.max,并在其中调用两次Math.random()函数,取两次Math.random方法中返回的最大值,那么如果任意两次返回结果 > x,都是无效的,只有两次的返回都 < 0.3 count才可以++, 那么就是x的平方。