is there a method which allows me to generate a boolean based on some percentages?
For example I need a generator which has a 25% chance of giving me false.
Right now I am doing :
val rand = new Random()
val a = List(true,true,true,false)
val isFailure = a(rand.nextInt(4))
I am doing this to get my "25%" chance of failure but I am not sure if this is the correct way and I am pretty sure there is a better way.
Can someone guide me on where to look or how to do it?
In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.
The best way to generate random bool is to use the MSB bit. This is actually a standard Bernoulli distribution with probability 1/2 . Save this answer.
Use random. getrandbits() to get a random boolean value Call random. getrandbits(k) with k set to 1 to get a single random bit. A bit is either 0 (representing False ) or 1 (representing True ). Use bool() to convert the random bit into a bool.
If you want to create a random boolean, use this code: var random = new Random(); var randomBool = random.
This:
math.random < 0.25
will yield true with a 0.25 probability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With