Bifrost
Bifrost

Reputation: 177

Why is C#'s random lower limit inclusive, but upper limit exclusive?

Take this code for example:

Random rnd = new Random();
int rndNumber = rnd.Next(0,101);

One would expect that either one of the following would happen:
-rndNumber contains a random integer between 0 and 101
-rndNumber contains a random integer between 1 and 100

What actually happens though, is that rndNumber contains a random integer between 0 and 100. Why is this the case?

I understand that the upper limit is exclusive, but then why is the lower limit inclusive? Why is this not consistent?

Upvotes: 8

Views: 2740

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726699

This approach is consistent with numbering schemes that use zero as their initial element. This is convenient in several situations, because you do not have to do any arithmetic or face rare off-by-one errors, for example

When you pick a random element of an array:

var rndElement = myArray[rnd.Next(0, myArray.Length)];

When you split an interval at several points, and pick random elements from each sub-interval:

var endpoints = new[] {0, 10, 17, 36, 80};
for (int i = 0 ; i+1 < endpoints.Length ; i++) {
    var from = endpoints[i];
    var to = endpoints[i+1];
    Console.WriteLine("({0}..{1}) : {2}", from , to, rnd.Next(from, to));
}

It also makes it easier to compute how many different values can be generated.

Upvotes: 11

Related Questions