Export (0) Print
Expand All

Random.Next Method ()

Returns a nonnegative random number.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public virtual int Next ()
public int Next ()
public function Next () : int
Not applicable.

Return Value

A 32-bit signed integer greater than or equal to zero and less than MaxValue.

Random.Next generates a random number whose value ranges from zero to 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: Starting with the .NET Framework version 2.0, 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.

The following code example generates random integers with various overloads of the Next method.

// Example of the Random.Next( ) methods.
using System;

public class RandomNextDemo  
{
    // Generate random numbers with no bounds specified.
    static void NoBoundsRandoms( int seed )
    {
        Console.WriteLine( 
            "\nRandom object, seed = {0}, no bounds:", seed );
        Random randObj = new Random( seed );

        // Generate six random integers from 0 to int.MaxValue.
        for( int j = 0; j < 6; j++ )
            Console.Write( "{0,11} ", randObj.Next( ) );
        Console.WriteLine( );
    }

    // Generate random numbers with an upper bound specified.
    static void UpperBoundRandoms( int seed, int upper )
    {
        Console.WriteLine( 
            "\nRandom object, seed = {0}, upper bound = {1}:", 
            seed, upper );
        Random randObj = new Random( seed );

        // Generate six random integers from 0 to the upper bound.
        for( int j = 0; j < 6; j++ )
            Console.Write( "{0,11} ", randObj.Next( upper ) );
        Console.WriteLine( );
    }

    // Generate random numbers with both bounds specified.
    static void BothBoundsRandoms( int seed, int lower, int upper )
    {
        Console.WriteLine( 
            "\nRandom object, seed = {0}, lower = {1}, " +
            "upper = {2}:", seed, lower, upper );
        Random randObj = new Random( seed );

        // Generate six random integers from the lower to 
        // upper bounds.
        for( int j = 0; j < 6; j++ )
            Console.Write( "{0,11} ", 
                randObj.Next( lower, upper) );
        Console.WriteLine( );
    }

    static void Main( )
    {	
        Console.WriteLine(                 
            "This example of the Random.Next( ) methods\n" +
            "generates the following output.\n" );
        Console.WriteLine(                 
            "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." );
    	
        NoBoundsRandoms( 234 );

        UpperBoundRandoms( 234, Int32.MaxValue );
        UpperBoundRandoms( 234, 2000000000 );
        UpperBoundRandoms( 234, 200000000 );

        BothBoundsRandoms( 234, 0, Int32.MaxValue );
        BothBoundsRandoms( 234, Int32.MinValue, Int32.MaxValue );
        BothBoundsRandoms( 234, -2000000000, 2000000000 );
        BothBoundsRandoms( 234, -200000000, 200000000 );
        BothBoundsRandoms( 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
*/

// Example of the Random.Next( ) methods.
import System.*;

public class RandomNextDemo
{
    // Generate random numbers with no bounds specified.
    static void NoBoundsRandoms(int seed)
    {
        Console.WriteLine("\nRandom object, seed = {0}, no bounds:",
            System.Convert.ToString(seed));
        Random randObj = new Random(seed);

        // Generate six random integers from 0 to int.MaxValue.
        for (int j = 0; j < 6; j++) {
            Console.Write("{0,11} ", System.Convert.ToString(randObj.Next()));
        }
        Console.WriteLine();
    } //NoBoundsRandoms

    // Generate random numbers with an upper bound specified.
    static void UpperBoundRandoms(int seed, int upper)
    {
        Console.WriteLine("\nRandom object, seed = {0}, upper bound = {1}:", 
            System.Convert.ToString(seed), System.Convert.ToString(upper));
        Random randObj = new Random(seed);

        // Generate six random integers from 0 to the upper bound.
        for (int j = 0; j < 6; j++) {
            Console.Write("{0,11} ",
                System.Convert.ToString(randObj.Next(upper)));
        }
        Console.WriteLine();
    } //UpperBoundRandoms

    // Generate random numbers with both bounds specified.
    static void BothBoundsRandoms(int seed, int lower, int upper)
    {
        Console.WriteLine("\nRandom object, seed = {0}, lower = {1}, "
            + "upper = {2}:", System.Convert.ToString(seed),
            System.Convert.ToString(lower), System.Convert.ToString(upper));
        Random randObj = new Random(seed);
        // Generate six random integers from the lower to 
        // upper bounds.
        for (int j = 0; j < 6; j++) {
            Console.Write("{0,11} ",
                System.Convert.ToString(randObj.Next(lower, upper)));
        }
        Console.WriteLine();
    } //BothBoundsRandoms

    public static void main(String[] args)
    {
        Console.WriteLine(("This example of the Random.Next( ) methods\n" 
            + "generates the following output.\n"));
        Console.WriteLine(("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."));
        NoBoundsRandoms(234);
        UpperBoundRandoms(234, Int32.MaxValue);
        UpperBoundRandoms(234, 2000000000);
        UpperBoundRandoms(234, 200000000);
        BothBoundsRandoms(234, 0, Int32.MaxValue);
        BothBoundsRandoms(234, Int32.MinValue, Int32.MaxValue);
        BothBoundsRandoms(234, -2000000000, 2000000000);
        BothBoundsRandoms(234, -200000000, 200000000);
        BothBoundsRandoms(234, -2000, 2000);
    } //main
} //RandomNextDemo

/*
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.

// Example of the Random.Sample( ) method.
using System;

// This derived class converts the uniformly distributed random 
// numbers generated by base.Sample( ) to another distribution.
public class RandomProportional : Random
{
    // Sample 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 class RandomSampleDemo  
{
    static void Main( )
    {	
        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 ];

        Console.WriteLine( 
            "This example of Random.Sample( ) " +
            "generates the following output." );
        Console.WriteLine( 
            "\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 the number values. " +
            "For example, \nnumbers are generated in the " +
            "vicinity of 0.75 with three times the \n" +
            "probability of those generated near 0.25." );
        Console.WriteLine( 
            "\nRandom doubles generated with the NextDouble( ) " +
            "method:\n" );

        // Generate and display [rows * cols] random doubles.
        for( int i = 0; i < rows; i++ )
        {
            for( int j = 0; j < cols; j++ )
                Console.Write( "{0,12:F8}", randObj.NextDouble( ) );
            Console.WriteLine( );
        }

        Console.WriteLine( 
            "\nRandom integers generated with the Next( ) " +
            "method:\n" );

        // Generate and display [rows * cols] random integers.
        for( int i = 0; i < rows; i++ )
        {
            for( int j = 0; j < cols; j++ )
                Console.Write( "{0,12}", randObj.Next( ) );
            Console.WriteLine( );
        }

        Console.WriteLine( 
            "\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 );
        Console.WriteLine( 
            "{0,21}{1,10}{2,20}{3,10}", "Integer Range",
            "Count", "Double Range", "Count" );
        Console.WriteLine( 
            "{0,21}{1,10}{2,20}{3,10}", "-------------",
            "-----", "------------", "-----" );

        // 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++ )
            Console.WriteLine( 
                "{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 ] );
    }
}

/*
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 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.70274545  0.71861388  0.68071795  0.84034066  0.93354743  0.85663774
  0.81804688  0.35177836  0.59208519  0.96031602  0.80442745  0.68718948
  0.98765094  0.88136820  0.40016694  0.78735843  0.30468930  0.60884722
  0.99724610  0.64792400  0.87542366  0.86193142  0.88573527  0.67682807

Random integers generated with the Next( ) method:

  2143307129  1985560852  1491542209  1624708626   545912171  2144440214
  1605065299  1294719830  1191410879  1120886902  1915435155  1514194175
  1795364867  1695595242  1754564804  1407165303  2026939619  1965958920
  1531822446  1145720706  1458838319  1924643339   804498107   445927707

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,916     0.00000-0.10000    10,014
 214748364- 429496728    29,978     0.10000-0.20000    29,965
 429496729- 644245093    50,204     0.20000-0.30000    49,975
 644245094- 858993458    69,870     0.30000-0.40000    70,150
 858993459-1073741823    89,875     0.40000-0.50000    90,180
1073741824-1288490187   110,448     0.50000-0.60000   109,995
1288490188-1503238552   130,290     0.60000-0.70000   130,218
1503238553-1717986917   149,652     0.70000-0.80000   149,300
1717986918-1932735282   170,367     0.80000-0.90000   169,737
1932735283-2147483647   189,400     0.90000-1.00000   190,466
*/

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2014 Microsoft