Jack Bauer
Jack Bauer

Reputation: 65

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

Upvotes: 4

Views: 2737

Answers (4)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

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; 

Upvotes: 8

D&#225;vid Florek
D&#225;vid Florek

Reputation: 571

Simple Unity solution:

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

Upvotes: 1

Alisson Reinaldo Silva
Alisson Reinaldo Silva

Reputation: 10705

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.

Upvotes: 1

Teodor Kurtev
Teodor Kurtev

Reputation: 1049

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

Upvotes: 3

Related Questions