Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

random

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?

like image 358
Bifrost Avatar asked Mar 27 '15 14:03

Bifrost


People also ask

Why is C language called C?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".

What is C language called?

C is an imperative, procedural language in the ALGOL tradition. It has a static type system. In C, all executable code is contained within subroutines (also called "functions", though not in the sense of functional programming).

Why is C such an important language?

C is a procedural language that supports structured programming; it has a static system and a compiler written in C itself. Since its release, C became a milestone of computing history and has become the most critical component throughout the computer industry.

Why C is called simple language?

The language itself has very few keywords, and most things are done using libraries, which are collections of code made to be reused. C has a big standard library called stdio, which stands for standard input/output.


1 Answers

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.

like image 180
Sergey Kalinichenko Avatar answered Nov 14 '22 21:11

Sergey Kalinichenko