Random boolean with weight or bias

2019-01-25 04:37发布

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 Random random = new Random();
random.nextBoolean();

will not work.

One possible solution would be:

private Random random = new Random()

public boolean getRandomBoolean(float p){
return random.nextFloat() < p;
}

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

EDIT: I guess I am asking whether there is a library class that provides a nextBoolean(float probability) method.

8条回答
叛逆
2楼-- · 2019-01-25 05:09

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.

查看更多
仙女界的扛把子
3楼-- · 2019-01-25 05:12

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();
查看更多
登录 后发表回答