Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random double number in the inclusive [0,1] range? [duplicate]

Tags:

c#

random

The following code generates a double number in the range [0,1) which means that 1 is exclusive.

var random = new Random();
random.NextDouble();

I am looking for some smart way to generate a random double number in the range [0,1]. It means that 1 is inclusive. I know that the probability of generating 0 or 1 is really low, but imagine that I want to implement a correct mathematical function that requires from me the inclusive limits. How can I do it?

The question is: What is the correct way of generating random in the range [0,1]. If there is no such way, I would love to learn it also.

like image 747
Mateusz Kopij Avatar asked Oct 23 '25 13:10

Mateusz Kopij


1 Answers

The Random.Next method returns an integer value in the range [0..Int32.MaxValue) (the exclusive range-end is denoted by the right parenthesis). So if you want to make the value 1.0 a possible result of the NextDouble method (source code), you could do this:

/// <summary>Returns a random floating-point number that is greater than or equal to 0.0,
/// and less than or equal to 1.0.</summary>
public static double NextDoubleInclusive(this Random random)
{
    return (random.Next() * (1.0 / (Int32.MaxValue - 1)));
}

This fiddle verifies that the expression (Int32.MaxValue - 1) * (1.0 / (Int32.MaxValue - 1)) evaluates to 1.0.

like image 151
Theodor Zoulias Avatar answered Oct 25 '25 03:10

Theodor Zoulias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!