首页 / JAVA / Java-随机数生成器中的缺陷
Java-随机数生成器中的缺陷
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java-随机数生成器中的缺陷,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2090字,纯文字阅读大概需要3分钟。
内容图文
![Java-随机数生成器中的缺陷](/upload/InfoBanner/zyjiaocheng/686/363669b83011402b9a5f72cefc61c16b.jpg)
我正在创建一个程序,该程序应随机指定我的Java中期将要解决的问题.
我创建了一个运行100,000次的程序,并将每个问题作为键输入到哈希图中,
而它的值是100,000中产生的计数数.
我创建了以下简单程序:
public class randomChoice {
public static Map<Integer, Integer> dictionary = new HashMap<Integer, Integer>();
public static void randInt() {
Random rand = new Random();
int randomNum = rand.nextInt((33 - 1) + 1) + 1;
if (dictionary.containsKey(randomNum)) {
dictionary.put(randomNum, dictionary.get(randomNum) + 1);
} else {
dictionary.put(randomNum, 0);
}
}
public static void main(String[] args) {
int i = 0;
while (i < 100000) {
randInt();
i++;
}
System.out.println(dictionary);
Map.Entry<Integer, Integer> maxEntry = null;
for (Map.Entry<Integer, Integer> entry : dictionary.entrySet()) {
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) {
maxEntry = entry;
}
}
System.out.println("\nThe question I will be using for the midterm is " + maxEntry.getKey() + " with a total count of " + maxEntry.getValue());
int total = 0;
for (Map.Entry<Integer, Integer> entry : dictionary.entrySet()) {
total = entry.getValue() + total;
}
System.out.println("\nTotal: " + total);
}
}
当我尝试将我的HashMap的所有值加起来(这是为每一个问题生成的频率,即100,000个问题)时,我的问题就出现了.
这是生成的输出,
打印HashMap,
我将随机选择的问题的价值最高,
最后是所有HashMap值的总和:
> run randomChoice
{1=3038, 2=3025, 3=3009, 4=2945, 5=2996, 6=3049, 7=3004, 8=3078, 9=3011, 10=3012, 11=2995, 12=3041, 13=3116, 14=3015, 15=3029, 17=3058, 16=3141, 19=3045, 18=2976, 21=2988, 20=3065, 23=2943, 22=3106, 25=3025, 24=3093, 27=3092, 26=3058, 29=3018, 28=2981, 31=3035, 30=2970, 32=3007, 33=3003}
The question I will be using for the midterm is 16 with a total count of 3141
Total: 99967
>
我的问题是,为什么总数会达到99967,而不是100,000?
大概33短,似乎有点可疑,我有33个问题可供选择.
我在这里做错了什么?
我的缺陷在哪里可以帮助我准确地创建100,000个生成的随机数?
解决方法:
您正好是100,000个数字中的33个,因为当您第一次遇到33个地图条目中的每个条目时,您放置的是0,而不是1.这是一个不一样的错误.
更改
dictionary.put(randomNum, 0);
至
dictionary.put(randomNum, 1);
内容总结
以上是互联网集市为您收集整理的Java-随机数生成器中的缺陷全部内容,希望文章能够帮你解决Java-随机数生成器中的缺陷所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。