免责声明:我不想要这个问题的答案。我只是需要一些指导。
我想使用 HashSet
对臭名昭著的生日悖论(确定给定组中至少 2 个人生日相同的概率)执行蒙特卡罗分析。
现在,当我运行它时,collisionCount
比我预期的要低很多。首先,我期望 10 人一组的 collisionCount
11446(或概率为 0.11446)。然后当我达到 100 人时,我预计 collisionCount 为 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 社区的新手,仍在学习中。非常感谢任何帮助/建议/提示。
最佳答案
您的问题似乎是您缺少一个循环。
请注意,您的 runs
循环因第一次碰撞而中断。这意味着您的值(value)永远不会超过 1。
此外,除非输出结果,否则永远不要在内循环中使用 people
变量。
您需要做的是运行模拟 100_000
次。这样做的方法是在您的 runs
循环中放置逻辑,检查 people
人是否会发生生日碰撞,然后迭代您的碰撞计数。
关于java - 使用 HashSet 对生日悖论进行蒙特卡罗分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29551879/