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
).
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;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With