Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random generation with very low chances

Tags:

c#

random

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?

like image 530
Sebb Avatar asked May 07 '14 15:05

Sebb


2 Answers

EDIT

Random.NextDouble() will not give the expected results!

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);

Original answer

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.

like image 163
Rik Avatar answered Sep 18 '22 17:09

Rik


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.

like image 30
Antonio Ragagnin Avatar answered Sep 19 '22 17:09

Antonio Ragagnin