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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 00:42:58  来源:igfitidea点击:

Java: How do I simulate probability?

javaprobability

提问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 Randomclass 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

First you need to create an instance of Randomsomewhere sensible in your program - for example when your program starts.

首先,您需要Random在程序中某个合理的地方创建一个实例- 例如,当您的程序启动时。

Random random = new Random();

Use this code to see whether an event happens:

使用此代码查看事件是否发生:

boolean happens = random.NextDouble() < prob;

回答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));
    }
}