The only thing I'd add to Eric's response is an explanation; I feel that knowledge of why code works is better than knowing what code works.
The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). NextDouble
only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and range.
So, this would give us random doubles between 0.0 and 2.0:
rng.NextDouble() * 2.0
But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:
2.5 + rng.NextDouble() * 2.0
Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.
At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:
double NextDouble(Random rng, double min, double max)
{
return min + (rng.NextDouble() * (max - min));
}
The default seed is taken from the system clock.
I'm guessing that your GetRandomRectangle
method was being called in quick succession and instantating a new instance of Random
each time. When you do this, each instance of Random
will take the same seed from the system clock, which is why your method created the same rectangle each time.
One solution is to create one instance of Random
and pass that into your method:
Random rng = new Random();
Rectangle foo = GetRandomRectangle(rng);
Rectangle bar = GetRandomRectangle(rng);
Rectangle baz = GetRandomRectangle(rng);
// ...
public Rectangle GetRandomRectangle(Random rng)
{
// create the rectangle using rng
}
Best Answer
According to the documentation,
Next
returns an integer random number between the (inclusive) minimum and the (exclusive) maximum:The only integer number which fulfills
is
0
, hence you always get the value0
. In other words,0
is the only integer that is within the half-closed interval[0, 1)
.So, if you are actually interested in the integer values
0
or1
, then use2
as upper bound:If instead you want to get a decimal between 0 and 1, try: