FlyBoy
FlyBoy

Reputation: 1175

C# Random.Next - never returns the upper bound?

random.Next(0,5)

It never returns the 5 (but sometimes returns the 0.) Why? I thought these are just boundary values that can be returned. Thanks

Upvotes: 83

Views: 58227

Answers (6)

user7969
user7969

Reputation: 41

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!

Upvotes: 1

Dork
Dork

Reputation: 1886

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.

Upvotes: 2

Kurt
Kurt

Reputation: 5

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.

Upvotes: -2

Marlon
Marlon

Reputation: 20312

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).

Upvotes: 7

Albin Sunnanbo
Albin Sunnanbo

Reputation: 47058

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.

Upvotes: 14

Mark Cidade
Mark Cidade

Reputation: 99957

The maxValue for the upper-bound in the Next() method is exclusive—the range includes minValue, maxValue-1, and all numbers in between.

Upvotes: 160

Related Questions