Random Number Between 2 Double Numbers

CodeLikeBeaker picture CodeLikeBeaker · Jun 30, 2009 · Viewed 208.2k times · Source

Is it possible to generate a random number between 2 doubles?

Example:

public double GetRandomeNumber(double minimum, double maximum)
{
    return Random.NextDouble(minimum, maximum) 
}

Then I call it with the following:

double result = GetRandomNumber(1.23, 5.34);

Any thoughts would be appreciated.

Answer

Michael picture Michael · Jun 30, 2009

Yes.

Random.NextDouble returns a double between 0 and 1. You then multiply that by the range you need to go into (difference between maximum and minimum) and then add that to the base (minimum).

public double GetRandomNumber(double minimum, double maximum)
{ 
    Random random = new Random();
    return random.NextDouble() * (maximum - minimum) + minimum;
}

Real code should have random be a static member. This will save the cost of creating the random number generator, and will enable you to call GetRandomNumber very frequently. Since we are initializing a new RNG with every call, if you call quick enough that the system time doesn't change between calls the RNG will get seeded with the exact same timestamp, and generate the same stream of random numbers.