概述
用Java的Math.random()方法生成随机数。此方法为真随机。
代码
public static void main(String[] args) {
int size = 100;
int cycle = 1000000;
int count = 0;
int target = 1;
for(int i = 0; i < cycle; i++){
int r = (int) (Math.random() * size);
if(r == target){
count++;
}
}
System.out.println((((double) count/cycle) * 100) + "%");
}
输出是1.0052%
验证真随机
public static void main(String[] args) {
int size = 10;
int cycle = 1000000;
int count = 0;
int target = 1;
int[] counts = new int[size];
for(int i = 0; i < cycle; i++){
int r = (int) (Math.random() * size);
counts[r]++;
}
for (int i = 0; i < counts.length; i++) {
System.out.println(i + "出现的概率:" + (double) counts[i]/cycle);
}
}
输出结果
从结果可以看出每个元素出现的概览相同。