Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random boolean with weight or bias

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.

like image 677
maxf130 Avatar asked Sep 05 '25 02:09

maxf130


2 Answers

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.
like image 152
Oliver Charlesworth Avatar answered Sep 06 '25 15:09

Oliver Charlesworth


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

like image 36
luksch Avatar answered Sep 06 '25 16:09

luksch