Am I missing something here? I am writing a game that requires some random number generation. I decided to use the System.Random class but I was getting strange results. The documentation says that if I have an instance of the class (let's call it r), the call

r.Next(1,6)

returns a random number in the range [1,6]. I always check random functions of this sort to ensure the accuracy of the "randomness". In this case I created a simple form with one button and the following code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

	Dim r As New System.Random
	Dim i, j As Integer
	Dim counts() As Integer = {0, 0, 0, 0, 0, 0, 0}

	Randomize()

	For i = 1 To 100000
		j = r.Next(1, 6)
		counts(j) += 1
	Next

	For i = 0 To 6
		Debug.WriteLine(i.ToString() & " = " & counts(i).ToString())
	Next

End Sub

This is the output that results:

0 = 0
1 = 19981
2 = 19950
3 = 20020
4 = 20041
5 = 20008
6 = 0

Clearly, the random numbers generated do not include the maxvalue (6) as stated in the intellisense popup. Am I missing something here? There is a famous quote that goes "the generation of random numbers is too important to be left to chance". If I am not missing something, and the random number generator is faulty then this is a giant oops on someone's part.

This is the actual text from the intellisense popup:

Public Overridable Function Next(minValue As Integer, maxValue As Integer) As Integer

Returns a random number within a specified range.

The intellisense documentation clearly gives the parameters as minValue and maxValue. Apparently Microsoft has redefined the meaning of min and max in the online documentation and example. It reminds me of the Excel bug where the year 1900 was considered a leap year. Microsoft didn't fix the bug. It seems to me that they've taken the same approach here. Don't fix the bug, just redefine the meaning of max.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.