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 04:46

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;
}
查看更多
来,给爷笑一个
3楼-- · 2019-01-25 04:56

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

The approach you're using already is fine.* AFAIK, there's not a standard Java method that will make this code any shorter.


* For non-cryptographic purposes.

查看更多
Animai°情兽
4楼-- · 2019-01-25 04: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

查看更多
可以哭但决不认输i
5楼-- · 2019-01-25 05:03

Here's what I'm using. Very similar to FracturedRetina's answer.

Random random = new Random();

// 20% chance
boolean true20 = (random.nextInt(5) == 0) ? true : false;

// 25% chance
boolean true25 = (random.nextInt(4) == 0) ? true : false;

// 40% chance
boolean true40 = (random.nextInt(5) < 2) ? true : false;
查看更多
成全新的幸福
6楼-- · 2019-01-25 05:08
    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...

查看更多
Anthone
7楼-- · 2019-01-25 05:08

Your way is probably better, code golf-wise, but another way to do it is like this:

public boolean getRandomBoolean() {
    Random random = new Random();
    //For 1 in 5
    int chanceOfTrue = 5;

    if (random.nextInt(chanceOfTrue) == 0) {
        return true;
    } else {
        return false;
    }
}

Or for 2 in 5, try this:

public boolean getRandomBoolean() {
    Random random = new Random();
    //For 2 in 5
    int chanceOfTrue = 5;
    int randInt = random.nextInt(chanceOfTrue);

    if (randInt == 0 || randInt == 1) {
        return true;
    } else {
        return false;
    }
}
查看更多
登录 后发表回答