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.
Watch out: if you're generating the
random
inside a loop like for examplefor(int i = 0; i < 10; i++)
, do not put thenew Random()
declaration inside the loop.From MSDN:
So based on this fact, do something as:
Doing this way you have the guarantee you'll get different double values.
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).
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.
You could use code like this:
If you need a random number in the range [
double.MinValue
;double.MaxValue
]Use instead: