Generating Random Numbers with Random


To generate a sequence of pseudorandom numbers, you will use the Random class. Sequences of random numbers are useful in a variety of situations, including simulations and modeling. The starting point of the sequence is determined by a seed value, which can be automatically provided by Random or explicitly specified.

Random defines these two constructors:

 public Random( ) public Random(int seed)

The first version creates a Random object that uses the system time to compute the seed value. The second uses the value of seed as the seed value.

Random defines the methods shown in Table 20-14.

Table 20-14: Methods Defined by Random

Method

Meaning

public virtual int Next( )

Returns the next random integer, which will be between 0 and Int32.MaxValue1, inclusive.

public virtual int Next(int upperBound)

Returns the next random integer that is between 0 and upperBound1, inclusive.

public virtual int Next(int lowerBound, int upperBound)

Returns the next random integer that is between lowerBound and upperBound1, inclusive.

public virtual void NextBytes(byte[ ] buf)

Fills buf with a sequence of random integers. Each byte in the array will be between 0 and Byte.MaxValue1, inclusive.

public virtual double NextDouble( )

Returns the next random value from the sequence represented as a floating-point number that is greater than or equal to 0.0 and less than 1.0.

protected virtual double Sample( )

Returns the next random value from the sequence represented as a floating-point number that is greater than or equal to 0.0 and less than 1.0. To create a skewed or specialized distribution, override this method in a derived class.

Here is a program that demonstrates Random by creating a pair of computerized dice:

 // An automated pair of dice. using System; class RandDice {   public static void Main() {     Random ran = new Random();     Console.Write(ran.Next(1, 7) + " ");     Console.WriteLine(ran.Next(1, 7));   } }

Here are three sample runs:

 5 2 4 4 1 6

The program works by first creating a Random object. Then it requests the two random values, each between 1 and 6.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net