Reputation: 65
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
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
Reputation: 571
Simple Unity solution:
bool result = Random.Range(0f, 1f) < probability;
Upvotes: 1
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
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