Generate true or false boolean with probability

I have a percentage, for example 40%

. Id like to "roll the dice" and the result is based on probability. (for example, there is a 40%

possibility that it will true

).

+3


source to share


4 answers


Since it Random.NextDouble()

returns an evenly distributed [0..1)

(pseudo) random value over a range, you can try



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

 ...

 double probability = 0.40;

 bool result = random.NextDouble() < probability; 

      

+6


source


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;
    }

      

+3


source


Simple Unity solution:

bool result = Random.Range(0f, 1f) < probability;

      

+1


source


You can use the built-in Random.NextDouble()

:

Returns a random floating point number that is greater than or equal to 0.0 and less than 1.0

Then you can check if this number is greater than the probability value:

static Random random = new Random();

public static void Main()
{
    // call the method 100 times and print its result...
    for(var i = 1; i <= 100; i++)
        Console.WriteLine("Test {0}: {1}", i, ForgeItem(0.4));
}

public static bool ForgeItem(double probability)
{
    var randomValue = random.NextDouble();
    return randomValue <= probability;
}

      

Note that the same Random

instance
must be used . Here is an example Scripts .

0


source







All Articles