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.
What if one of the values is negative? Wouldn't a better idea be:
About generating the same random number if you call it in a loop a nifty solution is to declare the new Random() object outside of the loop as a global variable.
Notice that you have to declare your instance of the Random class outside of the GetRandomInt function if you are going to be running this in a loop.
“Why is this?” you ask.
Well, the Random class actually generates pseudo random numbers, with the “seed” for the randomizer being the system time. If your loop is sufficiently fast, the system clock time will not appear different to the randomizer and each new instance of the Random class would start off with the same seed and give you the same pseudo random number.
Source is here : http://www.whypad.com/posts/csharp-get-a-random-number-between-x-and-y/412/
You could do this:
Johnny5 suggested creating an extension method. Here's a more complete code example showing how you could do this:
Now you can call it as if it were a method on the
Random
class:Note that you should not create lots of new
Random
objects in a loop because this will make it likely that you get the same value many times in a row. If you need lots of random numbers then create one instance ofRandom
and re-use it.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.