[英]Generate true or false boolean with a probability
I have a percentage, for example 40%
. 我有一个百分比,例如
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
). (例如,有
40%
可能性是true
)。
Since Random.NextDouble()
returns uniformly distributed in [0..1)
range (pseudo)random value, you can try 由于
Random.NextDouble()
返回均匀分布在[0..1)
范围(伪)随机值中,您可以尝试
// 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;
}
简单的Unity解决方案
bool result = Random.Range(0f, 1f) < probability;
You can use the built-in Random.NextDouble()
: 您可以使用内置的
Random.NextDouble()
:
Returns a random floating-point number that is greater than or equal to 0.0, and less than 1.0
返回大于或等于0.0且小于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. 请注意,必须使用相同的
Random
实例 。 Here is the Fiddle example . 这是小提琴的例子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.