I'm trying to get a random bool in C# for a scientific project. The problem is that the chance of the bool being true must be around 10^-12 to 10^-14; the default random function only generates ints and a value between 0 and [u]int.max is far to small.
How can I generate a random boolean value with such a low chance of being true?
EDIT
As Kyle suggests in the comments below, the implementation of Random.NextDouble()
maps an int
to the interval [0.0 , 1.0), effectively making my code equivalent to r.Next( 0, Int32.MaxValue ) == 0
. Adding more zeroes to will not affect the probability of the result being false.
Use one of the other answers, or use this code to generate a ulong (range 0-18446744073709551615) from System.Random
.
var r = new Random();
var bytes = new byte[8];
r.NextBytes(bytes);
ulong result = BitConverter.ToUInt64(bytes, 0);
Warning: will not work as expected, do not use! Provided merely for context.
Use Random.NextDouble()
instead: the result is a double between 0.0 and 1.0
var r = new Random();
var probablyFalseBool = r.NextDouble() < 0.0000000000001;
Vary the number of zeroes if necessary.
Try combining more than one random selection:
if(rnd.Next(0,10000) == 0 && rnd.Next(0,10000) == 0 && rnd.Next(0,10000) == 0){
}
Not sure if the C# syntax is correct, but this enter the if block with a probability of 10^-12.
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