Random boolean with weight or bias

前端 未结 8 699
鱼传尺愫
鱼传尺愫 2020-12-01 23:42

I need to generate some random booleans. However I need to be able to specify the probability of returning true. As a results doing:

private R         


        
相关标签:
8条回答
  • 2020-12-01 23:53

    I was wondering if there is a better or more natural way of doing this.

    The approach you're using already is fine.

    * As far as I know, there's not a standard Java method that will make this code any shorter.


    * For non-cryptographic purposes.

    0 讨论(0)
  • 2020-12-01 23:54
        public boolean getBiasedRandom(int bias) {
          int c;
          Random t = new Random();
         // random integers in [0, 100]
          c=t.nextInt(100);
          if (c>bias){return false;
          }
          else{return true;}
          }
    

    This one is based on percentage...

    0 讨论(0)
  • 2020-12-01 23:57

    1) Yes, i think your approach is valid and I don't see another easier way.

    2) There is a library for handling random numbers of different statistical distributions:

    http://introcs.cs.princeton.edu/java/22library/StdRandom.java.html

    0 讨论(0)
  • 2020-12-01 23:59

    Expanding on user2495765's answer, you can make a function which takes an input ratio (as two values chance:range see code)

    public class MyRandomFuncs {
        public Random rand = new Random();
    
        boolean getBooleanAsRatio(int chance, int range) {
            int c = rand.nextInt(range + 1);
            return c > chance;
        }
    

    }

    Depending on what you intend to do, you probably don't want to initalize Random from within your method but rather use as a class variable (as in the code above) and call nextInt() from within your function.

    0 讨论(0)
  • 2020-12-02 00:04

    The MockNeat library implements this feature.

    Example for generating a boolean value that has 99.99% of being true:

    MockNeat m = MockNeat.threadLocal();
    boolean almostAlwaysTrue = m.bools().probability(99.99).val();
    
    0 讨论(0)
  • 2020-12-02 00:07

    Random object needs to be intialized already.

    public static boolean flipRandom(double probability) {
        Validate.isBetween(probability, 0, 1, true);
        if(probability == 0)
            return false;
        if(probability == 1)
            return true;
        if(probability == 0.5)
            return random.nextBoolean();
        return random.nextDouble() < probability ? true : false;
    }
    
    0 讨论(0)
提交回复
热议问题