Random.Next Method
Microsoft Silverlight will reach end of support after October 2021. Learn more.
Returns a nonnegative random number.
Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Syntax
'Declaration
Public Overridable Function Next As Integer
public virtual int Next()
Return Value
Type: System.Int32
A 32-bit signed integer greater than or equal to zero and less than MaxValue.
Remarks
Random.Next generates a random number whose value ranges from zero to less than Int32.MaxValue. To generate a random number whose value ranges from zero to some other positive number, use the Random.Next(Int32) method overload. To generate a random number within a different range, use the Random.Next(Int32, Int32) method overload.
Notes to Inheritors
If you derive a class from Random and override the Sample method, the distribution provided by the derived class implementation of the Sample method is not used in calls to the base class implementation of the Random.Next method. Instead, the uniform distribution returned by the base Random class is used. This behavior improves the overall performance of the Random class. To modify this behavior to call the Sample method in the derived class, you must also override the Random.Next method.
Examples
The following code example generates random integers with various overloads of the Next method.
' Example of the Random.Next( ) methods.
Module Example
' Generate random numbers with no bounds specified.
Sub NoBoundsRandoms(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal seed As Integer)
outputBlock.Text &= String.Format(vbCrLf & _
"Random object, seed = {0}, no bounds:", seed) & vbCrLf
Dim randObj As New Random(seed)
' Generate six random integers from 0 to int.MaxValue.
Dim j As Integer
For j = 0 To 5
outputBlock.Text &= String.Format("{0,11} ", randObj.Next())
Next j
outputBlock.Text &= vbCrLf
End Sub
' Generate random numbers with an upper bound specified.
Sub UpperBoundRandoms(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal seed As Integer, ByVal upper As Integer)
outputBlock.Text &= String.Format(vbCrLf & _
"Random object, seed = {0}, upper bound = {1}:", _
seed, upper) & vbCrLf
Dim randObj As New Random(seed)
' Generate six random integers from 0 to the upper bound.
Dim j As Integer
For j = 0 To 5
outputBlock.Text &= String.Format("{0,11} ", randObj.Next(upper))
Next j
outputBlock.Text &= vbCrLf
End Sub
' Generate random numbers with both bounds specified.
Sub BothBoundsRandoms(ByVal outputBlock As System.Windows.Controls.TextBlock, _
ByVal seed As Integer, ByVal lower As Integer, ByVal upper As Integer)
outputBlock.Text &= String.Format(vbCrLf & _
"Random object, seed = {0}, lower = {1}, " & _
"upper = {2}:", seed, lower, upper) & vbCrLf
Dim randObj As New Random(seed)
' Generate six random integers from the lower to
' upper bounds.
Dim j As Integer
For j = 0 To 5
outputBlock.Text &= String.Format("{0,11} ", _
randObj.Next(lower, upper))
Next j
outputBlock.Text &= vbCrLf
End Sub
Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
outputBlock.Text &= String.Format( _
"This example of the Random.Next( ) methods" & _
vbCrLf & "generates the following output." & vbCrLf) & vbCrLf
outputBlock.Text &= String.Format( _
"Create Random objects all with the same seed " & _
"and generate" & vbCrLf & "sequences of numbers " & _
"with different bounds. Note the effect " & vbCrLf & _
"that the various combinations " & _
"of bounds have on the sequences.") & vbCrLf
NoBoundsRandoms(outputBlock, 234)
UpperBoundRandoms(outputBlock, 234, Int32.MaxValue)
UpperBoundRandoms(outputBlock, 234, 2000000000)
UpperBoundRandoms(outputBlock, 234, 200000000)
BothBoundsRandoms(outputBlock, 234, 0, Int32.MaxValue)
BothBoundsRandoms(outputBlock, 234, Int32.MinValue, Int32.MaxValue)
BothBoundsRandoms(outputBlock, 234, -2000000000, 2000000000)
BothBoundsRandoms(outputBlock, 234, -200000000, 200000000)
BothBoundsRandoms(outputBlock, 234, -2000, 2000)
End Sub
End Module
' This example of the Random.Next( ) methods
' generates the following output.
'
' Create Random objects all with the same seed and generate
' sequences of numbers with different bounds. Note the effect
' that the various combinations of bounds have on the sequences.
'
' Random object, seed = 234, no bounds:
' 2091148258 1024955023 711273344 1081917183 1833298756 109460588
'
' Random object, seed = 234, upper bound = 2147483647:
' 2091148258 1024955023 711273344 1081917183 1833298756 109460588
'
' Random object, seed = 234, upper bound = 2000000000:
' 1947533580 954563751 662424922 1007613896 1707392518 101943116
'
' Random object, seed = 234, upper bound = 200000000:
' 194753358 95456375 66242492 100761389 170739251 10194311
'
' Random object, seed = 234, lower = 0, upper = 2147483647:
' 2091148258 1024955023 711273344 1081917183 1833298756 109460588
'
' Random object, seed = 234, lower = -2147483648, upper = 2147483647:
' 2034812868 -97573602 -724936960 16350718 1519113864 -1928562472
'
' Random object, seed = 234, lower = -2000000000, upper = 2000000000:
' 1895067160 -90872498 -675150156 15227793 1414785036 -1796113767
'
' Random object, seed = 234, lower = -200000000, upper = 200000000:
' 189506716 -9087250 -67515016 1522779 141478503 -179611377
'
' Random object, seed = 234, lower = -2000, upper = 2000:
' 1895 -91 -676 15 1414 -1797
// Example of the Random.Next( ) methods.
using System;
public class Example
{
// Generate random numbers with no bounds specified.
static void NoBoundsRandoms(System.Windows.Controls.TextBlock outputBlock, int seed)
{
outputBlock.Text += String.Format(
"\nRandom object, seed = {0}, no bounds:", seed) + "\n";
Random randObj = new Random(seed);
// Generate six random integers from 0 to int.MaxValue.
for (int j = 0; j < 6; j++)
outputBlock.Text += String.Format("{0,11} ", randObj.Next());
outputBlock.Text += "\n";
}
// Generate random numbers with an upper bound specified.
static void UpperBoundRandoms(System.Windows.Controls.TextBlock outputBlock, int seed, int upper)
{
outputBlock.Text += String.Format(
"\nRandom object, seed = {0}, upper bound = {1}:",
seed, upper) + "\n";
Random randObj = new Random(seed);
// Generate six random integers from 0 to the upper bound.
for (int j = 0; j < 6; j++)
outputBlock.Text += String.Format("{0,11} ", randObj.Next(upper));
outputBlock.Text += "\n";
}
// Generate random numbers with both bounds specified.
static void BothBoundsRandoms(System.Windows.Controls.TextBlock outputBlock, int seed, int lower, int upper)
{
outputBlock.Text += String.Format(
"\nRandom object, seed = {0}, lower = {1}, " +
"upper = {2}:", seed, lower, upper) + "\n";
Random randObj = new Random(seed);
// Generate six random integers from the lower to
// upper bounds.
for (int j = 0; j < 6; j++)
outputBlock.Text += String.Format("{0,11} ",
randObj.Next(lower, upper));
outputBlock.Text += "\n";
}
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
outputBlock.Text += String.Format(
"This example of the Random.Next( ) methods\n" +
"generates the following output.\n") + "\n";
outputBlock.Text += String.Format(
"Create Random objects all with the same seed and " +
"generate\nsequences of numbers with different " +
"bounds. Note the effect\nthat the various " +
"combinations of bounds have on the sequences.") + "\n";
NoBoundsRandoms(outputBlock, 234);
UpperBoundRandoms(outputBlock, 234, Int32.MaxValue);
UpperBoundRandoms(outputBlock, 234, 2000000000);
UpperBoundRandoms(outputBlock, 234, 200000000);
BothBoundsRandoms(outputBlock, 234, 0, Int32.MaxValue);
BothBoundsRandoms(outputBlock, 234, Int32.MinValue, Int32.MaxValue);
BothBoundsRandoms(outputBlock, 234, -2000000000, 2000000000);
BothBoundsRandoms(outputBlock, 234, -200000000, 200000000);
BothBoundsRandoms(outputBlock, 234, -2000, 2000);
}
}
/*
This example of the Random.Next( ) methods
generates the following output.
Create Random objects all with the same seed and generate
sequences of numbers with different bounds. Note the effect
that the various combinations of bounds have on the sequences.
Random object, seed = 234, no bounds:
2091148258 1024955023 711273344 1081917183 1833298756 109460588
Random object, seed = 234, upper bound = 2147483647:
2091148258 1024955023 711273344 1081917183 1833298756 109460588
Random object, seed = 234, upper bound = 2000000000:
1947533580 954563751 662424922 1007613896 1707392518 101943116
Random object, seed = 234, upper bound = 200000000:
194753358 95456375 66242492 100761389 170739251 10194311
Random object, seed = 234, lower = 0, upper = 2147483647:
2091148258 1024955023 711273344 1081917183 1833298756 109460588
Random object, seed = 234, lower = -2147483648, upper = 2147483647:
2034812868 -97573602 -724936960 16350718 1519113864 -1928562472
Random object, seed = 234, lower = -2000000000, upper = 2000000000:
1895067160 -90872498 -675150156 15227793 1414785036 -1796113767
Random object, seed = 234, lower = -200000000, upper = 200000000:
189506716 -9087250 -67515016 1522779 141478503 -179611377
Random object, seed = 234, lower = -2000, upper = 2000:
1895 -91 -676 15 1414 -1797
*/
The following code example derives a class from Random to generate a sequence of random numbers whose distribution differs from the uniform distribution generated by the Sample method of the base class. It overrides the Sample method to provide the distribution of random numbers, and overrides the Random.Next method to use series of random numbers.
' This derived class converts the uniformly distributed random
' numbers generated by base.Sample( ) to another distribution.
Public Class RandomProportional
Inherits Random
' The Sample method generates a distribution proportional to the value
' of the random numbers, in the range [0.0, 1.0].
Protected Overrides Function Sample() As Double
Return Math.Sqrt(MyBase.Sample())
End Function
Public Overrides Function [Next]() As Integer
Return Sample() * Integer.MaxValue
End Function
End Class
Module Example
Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
Const rows As Integer = 4, cols As Integer = 6
Const runCount As Integer = 1000000
Const distGroupCount As Integer = 10
Const intGroupSize As Double = _
(CDbl(Integer.MaxValue) + 1.0) / _
CDbl(distGroupCount)
Dim randObj As New RandomProportional()
Dim intCounts(distGroupCount) As Integer
Dim realCounts(distGroupCount) As Integer
Dim i As Integer, j As Integer
outputBlock.Text &= vbCrLf & _
"The derived RandomProportional class overrides " & _
"the Sample method to " & vbCrLf & _
"generate random numbers in the range " & _
"[0.0, 1.0]. The distribution " & vbCrLf & _
"of the numbers is proportional to their numeric " & _
"values. For example, " & vbCrLf & _
"numbers are generated in the vicinity of 0.75 " & _
"with three times " & vbCrLf & "the " & _
"probability of those generated near 0.25." & vbCrLf
outputBlock.Text &= vbCrLf & _
"Random doubles generated with the NextDouble( ) " & _
"method:" & vbCrLf & vbCrLf
' Generate and display [rows * cols] random doubles.
For i = 0 To rows - 1
For j = 0 To cols - 1
outputBlock.Text &= String.Format("{0,12:F8}", randObj.NextDouble())
Next j
outputBlock.Text &= vbCrLf
Next i
outputBlock.Text &= vbCrLf & _
"Random integers generated with the Next( ) " & _
"method:" & vbCrLf & vbCrLf
' Generate and display [rows * cols] random integers.
For i = 0 To rows - 1
For j = 0 To cols - 1
outputBlock.Text &= String.Format("{0,12}", randObj.Next())
Next j
outputBlock.Text &= vbCrLf
Next i
outputBlock.Text &= String.Format(vbCrLf & _
"To demonstrate the proportional distribution, " & _
"{0:N0} random " & vbCrLf & _
"integers and doubles are grouped into {1} " & _
"equal value ranges. This " & vbCrLf & _
"is the count of values in each range:" & vbCrLf, _
runCount, distGroupCount) & vbCrLf
outputBlock.Text &= String.Format("{0,21}{1,10}{2,20}{3,10}", _
"Integer Range", "Count", "Double Range", "Count") & vbCrLf
outputBlock.Text &= String.Format("{0,21}{1,10}{2,20}{3,10}", _
"-------------", "-----", "------------", "-----") & vbCrLf
' Generate random integers and doubles, and then count
' them by group.
For i = 0 To runCount - 1
intCounts(Fix(CDbl(randObj.Next()) / _
intGroupSize)) += 1
realCounts(Fix(randObj.NextDouble() * _
CDbl(distGroupCount))) += 1
Next i
' Display the count of each group.
For i = 0 To distGroupCount - 1
outputBlock.Text &= String.Format( _
"{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}", _
Fix(CDbl(i) * intGroupSize), _
Fix(CDbl(i + 1) * intGroupSize - 1.0), _
intCounts(i), _
CDbl(i) / CDbl(distGroupCount), _
CDbl(i + 1) / CDbl(distGroupCount), _
realCounts(i)) & vbCrLf
Next i
End Sub
End Module
' This example of Random.Sample() generates the following output:
' The derived RandomProportional class overrides the Sample method to
' generate random numbers in the range [0.0, 1.0]. The distribution
' of the numbers is proportional to their numeric values. For example,
' numbers are generated in the vicinity of 0.75 with three times
' the probability of those generated near 0.25.
'
' Random doubles generated with the NextDouble( ) method:
'
' 0.28377004 0.75920598 0.33430371 0.66720626 0.97080243 0.27353772
' 0.17787962 0.54618410 0.08145080 0.56286100 0.99002910 0.64898614
' 0.27673277 0.99455281 0.93778966 0.76162002 0.70533771 0.44375798
' 0.55939883 0.87383136 0.66465779 0.77392566 0.42393411 0.82409159
'
' Random integers generated with the Next( ) method:
'
' 1364479914 1230312341 1657373812 1526222928 988564704 700078020
' 1801013705 1541517421 1146312560 338318389 1558995993 2027260859
' 884520932 1320070465 570200106 1027684711 943035246 2088689333
' 630809089 1705728475 2140787648 2097858166 1863010875 1386804198
'
' To demonstrate the proportional distribution, 1,000,000 random
' integers and doubles are grouped into 10 equal value ranges. This
' is the count of values in each range:
'
' Integer Range Count Double Range Count
' ------------- ----- ------------ -----
' 0- 214748363 9,892 0.00000-0.10000 9,928
' 214748364- 429496728 30,341 0.10000-0.20000 30,101
' 429496729- 644245093 49,958 0.20000-0.30000 49,964
' 644245094- 858993458 70,099 0.30000-0.40000 70,213
' 858993459-1073741823 90,801 0.40000-0.50000 89,553
' 1073741824-1288490187 109,699 0.50000-0.60000 109,427
' 1288490188-1503238552 129,438 0.60000-0.70000 130,339
' 1503238553-1717986917 149,886 0.70000-0.80000 150,000
' 1717986918-1932735282 170,338 0.80000-0.90000 170,128
' 1932735283-2147483647 189,548 0.90000-1.00000 190,347
using System;
// This derived class converts the uniformly distributed random
// numbers generated by base.Sample( ) to another distribution.
public class RandomProportional : Random
{
// The Sample method generates a distribution proportional to the value
// of the random numbers, in the range [0.0, 1.0].
protected override double Sample()
{
return Math.Sqrt(base.Sample());
}
public override int Next()
{
return (int)(Sample() * int.MaxValue);
}
}
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
const int rows = 4, cols = 6;
const int runCount = 1000000;
const int distGroupCount = 10;
const double intGroupSize =
((double)int.MaxValue + 1.0) / (double)distGroupCount;
RandomProportional randObj = new RandomProportional();
int[] intCounts = new int[distGroupCount];
int[] realCounts = new int[distGroupCount];
outputBlock.Text +=
"\nThe derived RandomProportional class overrides " +
"the Sample method to \ngenerate random numbers " +
"in the range [0.0, 1.0]. The distribution \nof " +
"the numbers is proportional to their numeric values. " +
"For example, \nnumbers are generated in the " +
"vicinity of 0.75 with three times the \n" +
"probability of those generated near 0.25." + "\n";
outputBlock.Text +=
"\nRandom doubles generated with the NextDouble( ) " +
"method:\n" + "\n";
// Generate and display [rows * cols] random doubles.
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
outputBlock.Text += String.Format("{0,12:F8}", randObj.NextDouble());
outputBlock.Text += "\n";
}
outputBlock.Text +=
"\nRandom integers generated with the Next( ) " +
"method:\n" + "\n";
// Generate and display [rows * cols] random integers.
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
outputBlock.Text += String.Format("{0,12}", randObj.Next());
outputBlock.Text += "\n";
}
outputBlock.Text += String.Format(
"\nTo demonstrate the proportional distribution, " +
"{0:N0} random \nintegers and doubles are grouped " +
"into {1} equal value ranges. This \n" +
"is the count of values in each range:\n",
runCount, distGroupCount) + "\n";
outputBlock.Text += String.Format(
"{0,21}{1,10}{2,20}{3,10}", "Integer Range",
"Count", "Double Range", "Count") + "\n";
outputBlock.Text += String.Format(
"{0,21}{1,10}{2,20}{3,10}", "-------------",
"-----", "------------", "-----") + "\n";
// Generate random integers and doubles, and then count
// them by group.
for (int i = 0; i < runCount; i++)
{
intCounts[(int)((double)randObj.Next() /
intGroupSize)]++;
realCounts[(int)(randObj.NextDouble() *
(double)distGroupCount)]++;
}
// Display the count of each group.
for (int i = 0; i < distGroupCount; i++)
outputBlock.Text += String.Format(
"{0,10}-{1,10}{2,10:N0}{3,12:N5}-{4,7:N5}{5,10:N0}",
(int)((double)i * intGroupSize),
(int)((double)(i + 1) * intGroupSize - 1.0),
intCounts[i],
((double)i) / (double)distGroupCount,
((double)(i + 1)) / (double)distGroupCount,
realCounts[i]) + "\n";
}
}
/*
This example of Random.Sample() displays the following output:
The derived RandomProportional class overrides the Sample method to
generate random numbers in the range [0.0, 1.0). The distribution
of the numbers is proportional to the number values. For example,
numbers are generated in the vicinity of 0.75 with three times the
probability of those generated near 0.25.
Random doubles generated with the NextDouble( ) method:
0.59455719 0.17589882 0.83134398 0.35795862 0.91467727 0.54022658
0.93716947 0.54817519 0.94685080 0.93705478 0.18582318 0.71272428
0.77708682 0.95386216 0.70412393 0.86099417 0.08275804 0.79108316
0.71019941 0.84205103 0.41685082 0.58186880 0.89492302 0.73067715
Random integers generated with the Next( ) method:
1570755704 1279192549 1747627711 1705700211 1372759203 1849655615
2046235980 1210843924 1554274149 1307936697 1480207570 1057595022
337854215 844109928 2028310798 1386669369 2073517658 1291729809
1537248240 1454198019 1934863511 1640004334 2032620207 534654791
To demonstrate the proportional distribution, 1,000,000 random
integers and doubles are grouped into 10 equal value ranges. This
is the count of values in each range:
Integer Range Count Double Range Count
------------- ----- ------------ -----
0- 214748363 10,079 0.00000-0.10000 10,148
214748364- 429496728 29,835 0.10000-0.20000 29,849
429496729- 644245093 49,753 0.20000-0.30000 49,948
644245094- 858993458 70,325 0.30000-0.40000 69,656
858993459-1073741823 89,906 0.40000-0.50000 90,337
1073741824-1288490187 109,868 0.50000-0.60000 110,225
1288490188-1503238552 130,388 0.60000-0.70000 129,986
1503238553-1717986917 149,231 0.70000-0.80000 150,428
1717986918-1932735282 170,234 0.80000-0.90000 169,610
1932735283-2147483647 190,381 0.90000-1.00000 189,813
*/
Version Information
Silverlight
Supported in: 5, 4, 3
Silverlight for Windows Phone
Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0
XNA Framework
Supported in: Xbox 360, Windows Phone OS 7.0
Platforms
For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.