我有一个百分比,例如40%
。我喜欢" 掷骰子"结果基于概率。 (例如,有40%
个机会成为true
)。
答案 0 :(得分:6)
由于Random.NextDouble()
返回均匀分布在[0..1)
范围(伪)随机值中,您可以尝试
// Simplest, but not thread safe
private static Random random = new Random();
...
double probability = 0.40;
bool result = random.NextDouble() < probability;
答案 1 :(得分:3)
您可以尝试这样的事情:
public static bool NextBool(this Random random, double probability = 0.5)
{
if (random == null)
{
throw new ArgumentNullException(nameof(random));
}
return random.NextDouble() <= probability;
}
答案 2 :(得分:1)
简单的Unity解决方案:
bool result = Random.Range(0f, 1f) < probability;
答案 3 :(得分:0)
您可以使用内置的Random.NextDouble()
:
返回大于或等于0.0且小于1.0
的随机浮点数
然后你可以测试这个数字是否大于概率值:
let empty = repeatElement(s, count: 0)
请注意必须使用相同的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;
}
实例。 Here is the Fiddle example