'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).



Solution 1:[1]

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; 

Solution 2:[2]

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

Solution 3:[3]

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 test whether the 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;
}

Take note the same Random instance must be used. Here is the Fiddle example.

Solution 4:[4]

Simple Unity solution:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Teodor Kurtev
Solution 3 Alisson Reinaldo Silva
Solution 4 Dávid Florek