Generate Random Boolean Probability

岁酱吖の 提交于 2019-12-03 10:45:42

问题


I only know how I can generate a random boolean value (true/false). The default probability is 50:50

But how can I generate a true false value with my own probability? Let's say it returns true with a probability of 40:60 or 20:80 etc...


回答1:


Well, one way is Random.Next(100) <= 20 ? true : false, using the integer value of NextInt to force your own probability. I can't speak to the true 'randomness' of this method though.

More detailed example:

Random gen = new Random();
int prob = gen.Next(100);
return prob <= 20;



回答2:


You generate a random number up to 100 exclusive and see if it's less than a given percent. Example:

if(random.Next(100) < 40) {
  // will be true 40% of the time
}

More generally, for a probability of X/Y, use an idiom like:

if(random.Next(Y) < X)



回答3:


Here is an extension method that will provide a random bool with specified probability (in percentage) of being true;

public static bool NextBool(this Random r, int truePercentage = 50)
{
    return r.NextDouble() < truePercentage / 100.0;
}

you can use this like

Random r = new Random();
r.NextBool(); // returns true or false with equal probability
r.NextBool(20); // 20% chance to be true;
r.NextBool(100); // always return true
r.NextBool(0); // always return false



回答4:


Assuming your probability is represented as double between 0.0 and 1.0, I would implement it more simply like this:

Random rand = new Random();
...
double trueProbability = 0.2;
bool result = rand.NextDouble() < trueProbability;

result will be true with the probability given by trueProbability

http://msdn.microsoft.com/en-us/library/system.random.nextdouble(v=vs.110).aspx

If this isn't "random enough", you can take a look at RNGCryptoServiceProvider:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx




回答5:


I think it can help you

Random gen = new Random();
bool result = gen.Next(100) < 50 ? true : false;



回答6:


For future knowledge:

40:60 would be:

var random = new Random();
return random.Next(10) < 4;

20:80 would be:

var random = new Random();
return random.Next(5) == 0

and 1:1 would be:

var random = new Random();
return random.Next(2) == 1;

Note: Just shorten the probability to the shortest variant - as for example: "random.Next(5) == 0" is quicker then "random.Next(100) <= 20 Though - if the probability changes from the user input - then it would look like:

[ModifierByChoice] bool GetProbability(int trueProbability, int falseProbability)
{
var random = new Random();
return random.Next(trueProbability, trueProbability + falseProbability) < trueProbability;
}



回答7:


Random gen = new Random();
var boolVal = gen.Next(0, 1)==1? true : false;


来源:https://stackoverflow.com/questions/25275873/generate-random-boolean-probability

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!