Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to generate a random boolean

So there is several ways of creating a random bool in C#:

  • Using Random.Next(): rand.Next(2) == 0
  • Using Random.NextDouble(): rand.NextDouble() > 0.5

Is there really a difference? If so, which one actually has the better performance? Or is there another way I did not see, that might be even faster?

like image 307
timedt Avatar asked Oct 04 '13 21:10

timedt


People also ask

How do you generate a random Boolean?

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.

How do you randomize a boolean in C#?

If you want to create a random boolean, use this code: var random = new Random(); var randomBool = random.


1 Answers

The first option - rand.Next(2) executes behind the scenes the following code:

if (maxValue < 0) {     throw new ArgumentOutOfRangeException("maxValue",         Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", new object[] { "maxValue" })); } return (int) (this.Sample() * maxValue); 

and for the second option - rand.NextDouble():

return this.Sample(); 

Since the first option contains maxValue validation, multiplication and casting, the second option is probably faster.

like image 59
Aviran Cohen Avatar answered Oct 01 '22 06:10

Aviran Cohen