Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate true or false boolean with a probability

I have a percentage, for example 40%. Id like to "throw a dice" and the outcome is based on the probability. (for example there is 40% chance it's going to be true).

like image 900
Jack Bauer Avatar asked Dec 19 '22 07:12

Jack Bauer


2 Answers

Since Random.NextDouble() returns uniformly distributed in [0..1) range (pseudo)random value, you can try

 // Simplest, but not thread safe   
 private static Random random = new Random();

 ...

 double probability = 0.40;

 bool result = random.NextDouble() < probability; 
like image 117
Dmitry Bychenko Avatar answered Dec 24 '22 01:12

Dmitry Bychenko


You can try something like this:

    public static bool NextBool(this Random random, double probability = 0.5)
    {
        if (random == null)
        {
            throw new ArgumentNullException(nameof(random));
        }

        return random.NextDouble() <= probability;
    }
like image 29
Teodor Kurtev Avatar answered Dec 24 '22 00:12

Teodor Kurtev