【问题标题】:Generating a discrete random variable in Java? [duplicate]在Java中生成离散随机变量? [复制]
【发布时间】:2022-01-07 12:37:09
【问题描述】:

今天在采访中他们问我这个问题?如何在 Java 中生成离散随机变量?我做不到,但我想知道解决方案。 他们给了我一个数组:

double[] probabilities={.2,.1,.3,.4};
double[] outcomes ={4,5,8,11.5};

这应该给出答案:

double discreteRV = problem.randPMF(probabilities,outcomes);

我不明白如何解决这个问题。

【问题讨论】:

    标签: java random


    【解决方案1】:

    由于所有概率加起来总是为 1,因此您可以生成一个介于 0 和 1 之间的随机数,然后遍历概率并减去它们。当数字小于等于0时,最后减去概率的索引就是结果的索引:

    import java.util.Random;
    
    public static double randPMF(double[] prob, double[] out) {
        double rand = Math.random();
        int index = -1;
        while (rand >= 0) {
            index++;
            rand -= prob[index];
        }
        return out[index];
    }
    

    【讨论】:

    • 看起来我们在概念上的想法基本相同。不过我认为你的可能更干净。
    • @xtratic 谢谢!伟大的思想都一样
    • 这段代码最终会抛出ArrayIndexOutOfBoundsExceptionMath.random() 最终会返回 0.0。用while (rand >= 0.0) 轻松修复。
    【解决方案2】:

    这是我的解决方案想法:

    private double randPMF(double[] probabilities, double[] outcomes) {
        double random = Math.random();
        double p = 0;
        for (int i = 0; i < probabilities.length; i++) {
            p += probabilities[i];
            if (random < p) {
                return outcomes[i];
            }
        }
        return outcomes[outcomes.length - 1];
    }
    

    【讨论】:

      【解决方案3】:

      这是我想出来的

          private static double randPMF(double[] probabilities, double[] outcomes) {
              int n = 10;
              boolean nNotFound;
              for (double probability: probabilities){
                  nNotFound = true;
                  while(nNotFound)
                  if (probability*n == (double)((int)(probability*n)))
                      break;
                  else
                      n *= 10;
              }
              double[] numbers = new double[n];
              //j tracks the probability/occurence
              int j;
              //k tracks the new array
              int k = 0;
              //i tracks each element in our old arrays
              for (int i = 0; i<probabilities.length; i++) {
                  j = 0;
                  while (j < (probabilities[i]*n)) {
                  numbers[k] = outcomes[i];
                  k++;
                  j++;
                  }
              }
              int index = new Random().nextInt(n);
              System.out.println(numbers.length);
              return numbers[index];
          }
      

      【讨论】:

      • 如果像.05这样的概率很小怎么办?我认为这在这种情况下行不通。
      • @xtratic 我已经通过使 n(我们创建的数组中的元素数)动态并取决于小数位数来解决这个问题。
      • @xtratic 我认为你的解决方案比我的效率高很多
      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2012-07-07
      • 2013-07-15
      • 2017-06-12
      相关资源
      最近更新 更多