【发布时间】:2015-06-15 14:36:31
【问题描述】:
免责声明:我不想要这个问题的答案。我只是需要一些指导。
我想使用 HashSet 对臭名昭著的生日悖论(确定给定组中至少 2 个人生日相同的概率)执行蒙特卡罗分析。
现在,当我运行此程序时,collisionCount 远低于我的预期。首先,我预计 10 人一组的 collisionCount 为 11446(或概率为 0.11446)。然后当我达到 100 人时,我预计碰撞计数为 100,000(概率为 1.0)。但是,对于每 10 人,collisionCount 仅按 1 计数(10 人:1 次碰撞,20 人:2 次碰撞,30 人:3 次碰撞,等等)。
这是我目前写的代码:
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class BirthdayParadox
{
public static void main(String [] args)
{
Random rand = new Random();
int tests = 100000;
int collisionCount = 0;
for(int people = 10; people <= 100; people += 10)
{
Set<Integer> birthdays = new HashSet<>(365);
birthdays.add(rand.nextInt(365));
for(int runs = 0; runs < tests; runs++)
{
int randomBirthday = rand.nextInt(365);
if(birthdays.contains(randomBirthday))
{
collisionCount++;
break;
}
birthdays.add(randomBirthday);
}
float prob = (float)collisionCount / tests;
System.out.println("After " + tests + " tests there were " +
collisionCount + " occurrences of shared " +
" birthdays in a set of " + people + " people.");
System.out.println("Probability : " + prob);
}
}
}
我想我的问题是:为了让 collisionCount 正确计数,我是否对我的任何一个 for 循环都没有做正确的事情?
我是学习 Java 的新手,我是 Stack Overflow 社区的新手,并且仍在学习中。非常感谢任何帮助/建议/提示。
【问题讨论】:
标签: java for-loop hashset montecarlo birthday-paradox