Java:我如何模拟概率?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10368202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How do I simulate probability?
提问by Adam Soffer
I have a set of over 100 different probabilities ranging from 0.007379 all the way to 0.913855 (These probabilities were collected from an actuary table http://www.ssa.gov/oact/STATS/table4c6.html). In Java, how can I use these probabilities to determine whether something will happen or not? Something along these lines...
我有一组超过 100 个不同的概率,范围从 0.007379 一直到 0.913855(这些概率是从精算表http://www.ssa.gov/oact/STATS/table4c6.html收集的)。在 Java 中,如何使用这些概率来确定某事是否会发生?沿着这些路线的东西......
public boolean prob(double probability){
if (you get lucky)
return true;
return false;
}
回答by Thorn
The Random
class allows you to create a consistent set of random numbers so that every time you run the program, the same sequence of values is generated. You can also generate normally distributed random values with the Random class. I doubt you need any of that.
该Random
级允许你让你每次运行程序时,产生的值相同的序列创建一个一致的随机数。您还可以使用 Random 类生成正态分布的随机值。我怀疑你需要这些。
For what you describe, I would just use Math.random. So, given the age of a man we could write something like:
对于你所描述的,我只会使用 Math.random。因此,考虑到一个人的年龄,我们可以这样写:
double prob = manDeathTable[age];
if( Math.random() < prob )
virtualManDiesThisYear();
回答by Mark Byers
回答by duffymo
I'm not sure where that range came from. If you have a distribution in mind, I'd recommend using a Random to generate a value and get on with it.
我不确定这个范围是从哪里来的。如果您有一个分布,我建议您使用 Random 来生成一个值并继续使用它。
public ProbabilityGenerator {
private double [] yourValuesHere = { 0.007379, 0.5, 0.913855 };
private Random random = new Random(System.currentTimeMillis());
public synchronized double getProbability() {
return this.yourValuesHere[this.random.nextInt(yourValuesHere.length));
}
}