tags:

views:

661

answers:

4

It is 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.

Thanks!

+26  A: 

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.

Michael
Just watch out if you call GetRandomNumber() in a loop as it will generate the same value over and over
John Rasch
@John - Good point, I added this to my answer.
Michael
perfect! this is what I was looking for. Thank you so much
Jason Heine
return new Random().NextDouble() * (maximum - minimum) + minimum; is how I'd return it since I'm not using "random" anywhere else in that function.
Zack
@Zack - Remember, though that the seed value is likely going to be the same if you use GetRandomNumber() repeatedly in a loop. If you call GetRandomNumber no more than once per millisecond, you should be ok. If you notice your random numbers are repeating, you'll know why.
Charlie Salts
+2  A: 

The simplest approach would simply generate a random number between 0 and the difference of the two numbers. Then add the smaller of the two numbers to the result.

Greg D
+1  A: 

You could use code like this:

public double getRandomNumber(double minimum, double maximum) {
    return minimum + randomizer.nextDouble() * (maximum - minimum);
}
Malcolm
A: 

You could do this:

public class RandomNumbers : Random
{
    public RandomNumbers(int seed) : base(seed) { }

    public double NextDouble(double minimum, double maximum)
    {
        return base.NextDouble() * (maximum - minimum) + minimum;
    }
}