C# Random.Next - never returns the upper bound?
random.Next(0,5)
It never returns the开发者_JAVA技巧 5 (but sometimes returns the 0.) Why? I thought these are just boundary values that can be returned. Thanks
The maxValue
for the upper-bound in the Next()
method is exclusive—the range includes minValue
, maxValue-1
, and all numbers in between.
The documentation says the upper bound is exclusive. Exclusive means that it is not included in the possible return set. In a more mathematical notation 0 <= x < 5
in this case.
Straight from the documentation:
Summary:
Returns a random number within a specified range.
Parameters:
minValue:
The inclusive lower bound of the random number returned.
maxValue:
The exclusive upper bound of the random number returned. maxValue must be
greater than or equal to minValue.
Returns:
A 32-bit signed integer greater than or equal to minValue and less than maxValue;
that is, the range of return values includes minValue but not maxValue. If
minValue equals maxValue, minValue is returned.
If you look at the parameters, you will see that minValue
is inclusive (which is why your 0 occurs) and maxValue
is exclusive (your 5 never occurs).
Good way to remember it is to consider max as amount of numbers from which it takes random number.
So random.Next(0,2)
means that it takes random out of 2 numbers starting from 0: 0 and 1.
This has been written a long time ago but I will comment anyway. I think the main reason for that design decision is that most if not all random number generator at their core generate numbers from 0 to 2^32-1. So if you specify Int32.MaxValue you will never get that number. Having an exception for one number must have been not acceptable to the designers so they decided to have the bracket exclusive. Problem solved!
When you just look in Google for "c# random" and follow the first links to the method of desire you get here: http://msdn.microsoft.com/en-us/library/aa329893(v=vs.71).aspx
And there is no hint about the exclusiveness of the upper bound. They must have found the mistake in the code and corrected it with documentation.
So it is important to always check the version of the framework when looking at the documentation. Even when working with old versions of the framework, it is worth to have a look at the newer documentation.
精彩评论