Log in Page Discussion History Go to the site toolbox

XNA Tutorials/Generate Random Numbers

From BluWiki

How to Generate Random Numbers in C#

Written by Weston Castleberg

Part of a series of XNA Tutorials.

The C# language supports a pseudorandom number generator. The numbers generated like this are called pseudorandom because they are produced by mathematical functions acting upon a seed value, which may or may not be random. However, for most purposes this is not an issue, because what really matters is that these numbers are unpredictable. For the purposes of this article, it will be assumed that every occurrence of the word "random" actually means "pseudorandom."

Instantiating a Random Number Generator

Random numbers can be generated in C# with an instance of the Random class. The Random class is located inside of the System namespace. An instance of Random can be initialized like this:

System.Random generator = new System.Random();

Generating Random Numbers

There are several member functions (or methods) contained within the Random class, which can be used to generate random numbers. They can be seen below.

The first three overloads all generate 32-bit signed integers.

//this overload of the Next function returns a 32-bit signed integer between 0 and 2147483647.
int rand = generator.Next();

//this overload of the Next function takes a 32-bit signed integer as a parameter and returns
//a 32-bit signed integer which is between 0 and the integer passed in.
rand = generator.Next(8312009);

//this overload of the Next function takes two 32-bit signed integers as parameters.  the first
//the parameter is the minimum value to be generated while the second parameter is the maximum value.
rand = generator.Next(0,8312009);

The next overload generates a floating point value.

//this overload of the Next function returns a floating point number between 0.0 and 1.0
double randf = generator.NextDouble();

Further Examples

As another example, in order to generate a random non-negative real number, which is less than 1000000, this code would work nicely:

randf = generator.Next(1000000) + generator.NextDouble();


Microsoft, MSDN Library, January 2009

Site Toolbox:

Personal tools
GNU Free Documentation License 1.2
This page was last modified on 10 September 2009, at 18:43.
Disclaimers - About BluWiki