Geekpedia Programming Tutorials






Generate Random Numbers using C#

This tutorial will take you through all you need to know about generating random numbers using C#.

On Thursday, October 18th 2007 at 09:40 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.3 with 21 votes)
Contextual Ads
More C# Resources
Advertisement

Pseudo-Random Numbers

Whether you're planning on building a game, looking to pick a lucky winner from an array of contest participants or simply want to display a random picture in your ASP.NET website, random numbers are something that you should know how to obtain, especially since in modern programming language it's so easy to. The dark truth behind computer generated random numbers however, is that they are not truly random, they are pseudo-random, generated by complex algorithms. But then again, for a long time scientists couldn't find anything random in the universe, and the current subjects that appear to be random are still debatable.

Without further ado, I present you what is needed in order to generate a random number in C#:


Random randNum = new Random();

randNum.Next();


That's all it takes. The creation of a Random object (of the System.Random class) and calling its Next() method, which is going to return a non-negative random number as an integer.


Random Numbers Within a Range

As soon as you test the code above, you realize it returns a quite large number. However, most of the time you'll want to generate a number between a desired range. For instance if in your contest 108 people participated, you'll want to generate a random no larger than 108:


Random randNum = new Random();

randNum.Next(108); // No larger than 108


This will generate you a positive number of up to 108, including 108. However in certain situations (such as picking the contest winner), you'll want the number to be 1 to 108, while the code above returns a number that is 0 to 108. Since people would probably not take kindly to you announcing that the winner is participant number 0, thanks to another overload of the Next() function, you will be able to specify a minimum value, as such:


Random randNum = new Random();

randNum.Next(1, 108); // No larger than 108, no smaller than 1



Using Seeds

C++ programmers and others may wonder what happened to the seed. Who's seeding this random number because you sure aren't? Well, in the default constructor of the Random() object that we've seen above, where no parameter was specified, a seed will be automatically generated for you based on the current system time (which should always be unique.) Not having to specify the system time yourself as a parameter is very convinient, since the great majority of programmers would do that when generating random numbers.

However, there are advantages to specifying your own seed. One important thing to note is that for as long as you specify the same seed, you will get the same random number. Let's look at an example:


Random randNum = new Random(1986);

randNum.Next(); // This will always generate 564610494


Here we specify a seed, more exactly the number 1986, in order to generate a random number based on that seed. However, what is the point of using this, when it always generates the same number? Check this out:


Random randNum = new Random(1986);

randNum.Next(); // This will always generate 564610494

randNum.Next(); // This will always generate 1174029081

randNum.Next(); // This will always generate 2057658224


The interesting concept behind this is that each time you apply the Next() method, it will come up with a different number, so more exactly you will get a sequence of random numbers, but since they're based on the same seed, whenever you use that seed again, you are guaranteed to get the same random numbers. Thus if we create a new Random object and pass the 1986 value, get some random values, then create another Random object and pass the same 1986 value as the seed, the same random numbers will be retrieved in the exact same sequence . I'm not going to get very deep into explaining this, but it's not hard to imagine where you would need this, and when you will need this (if ever), you'll know it.


Double-Precision Numbers

Sometimes you may want to generate double-precision numbers, and C# has a method for that. Instead of using Next(), the NextDouble() method will return a number between 0 and 1:


Random randNum = new Random();

randNum.NextDouble();

randNum.NextDouble();

randNum.NextDouble();


This will generate numbers such as 0.12820489450164194, 0.81203657295197121 and 0.0582018419231087554.

Now if you picked into IntelliSense, you've probably noticed a new method:


Array of Random Bytes

The NextBytes() method will fill an array of bytes with random bytes. Thus, each element of the array will be a byte with a value of 0 to 255:


byte[] randBytes = new byte[108];

Random randNum = new Random();

randNum.NextBytes(randBytes);


This code would produce an array with values as such: 196 231 77 225 52 144 146 72 3 90 18 233 161 205 147 196 35 152 30 220 41 114 156 25 184 185 30 64 140 138 215 62 178 90 158 94 0 47 101 234 151 44 71 189 146 113 111 90 3 93 59 104 91 143 81 82 75 51 40 123 113 81 188 121 130 212 55 71 47 52 195 243 50 52 68 252 42 222 135 70 74 196 61 46 79 111 227 34 8 75 19 205 6 234 120 70 112 206 58 190 58 39 42 206 153 71 53 38. But of course, since we don't specify a seed and the current system time is being used, you'll get a different set of values.

That's all for random numbers using C#.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by vgstudios owner on Friday, October 19th 2007 at 12:40 PM

exelent!!!!!!!!1

by Ravi Wallau on Monday, December 3rd 2007 at 10:37 AM

private GetNextRandom() {
Random r = new Random();
int next = r.Next();
}

There are two problems with this approach:
1. The Random object is created everytime the object is called, wasting system resources;
2. The default seed is not suitable if this method is called many times in a second. Two calls in the same second will retrieve the same value from this sample, because the seed to the Random (when using the default constructor) is the current second on system time.

http://msdn2.microsoft.com/en-us/library/system.random.aspx

The best approach, in my opinion, is to create a class to generate Random numbers with static methods, and you should also have a static Random class initialized only once.

by amith on Wednesday, April 16th 2008 at 02:44 AM

I want to generate an array 5 random numbers between a range ( say min to max).

by dekidshere on Thursday, May 22nd 2008 at 01:45 AM

gak ngerti !

by ste on Thursday, July 24th 2008 at 04:19 PM

nice tutorial, tq so much.

makasih2

by ada on Wednesday, July 30th 2008 at 01:34 PM

gini aja ga ngerti... cmn kek fungsi rand di C

by cecile on Monday, August 25th 2008 at 10:47 AM

we need to write a program about poker game...and they said we're going to use random function.

by Risto Karhu on Friday, January 9th 2009 at 09:38 AM

I use this for random generation. Random class should take 32 bit as random value but takes only 30 bits..dont know why. This generates random seed from system time.

1. Initalize App
2. Create Random class (only once in beginning of the app OR series of random numbers)
Random randobj = new Random(Convert.ToInt32(DateTime.Now.Ticks % 0x7FFFFFFF));
3. Exit

Works fine for me. 0x80000000 generates Overflow error. Not Random but the exakt value 0x800000.
So You should Only use values 0 to 0x7FFFFFFF as the seed. (0x7FFFFFFF = 2147483647 (decimal))

by Piotr on Monday, January 12th 2009 at 04:29 PM

Every results in this tutorial are not true. They are only true when you're debuging. Why look on
second point of Ravi Wallau comment.
This code
Random randNum = new Random();

randNum.NextDouble();

randNum.NextDouble();

randNum.NextDouble();

This will generate 3 equal doubles.

Commnet to Ravi Wallau.
"(when using the default constructor) is the current second on system time."
As far as I know is nanosecond = DataTime.Now.Ticks. However 2 point you made is correct.

My solution for finding random for some colection is pseudocode
for(int x=0;x<someCollection.length;x )
{
Random r= new Random(DateTime.Now.Ticks * (x 1));
r.getNextDouble();
}
Any ideas for more efficient solution. This solution
is wasting system resources ( random generated every step in loop).

by Piotr on Monday, January 12th 2009 at 04:32 PM

sry.. My solution is

My solution for finding random for some colection is pseudocode
for(int x=0;x<someCollection.length;x )
{
Random r= new Random(DateTime.Now.Ticks * (x 1));
r.getNextDouble();
}

.. so i'm creating seed using DateTime.Now.Ticks
and combining it with other value for each item in collection.

by Piotr on Monday, January 12th 2009 at 04:34 PM

Where da hell are " " characters

by Risto Karhu on Friday, January 16th 2009 at 05:37 AM

My solutution is for those cases you need a good "start" seed for a long series of random numbers, because the numbers in the random class is random itself. The most important thing is NOT to shuffle in the random number array BUT to get different startpoints in the random array.

So i think my solution is pretty good... i think the Random Class is misunderstood. Dont shuffle but get different starting points because the numbers NEXT to your starting poits IS random for your application.

by Risto Karhu on Friday, January 16th 2009 at 05:37 AM

My solutution is for those cases you need a good "start" seed for a long series of random numbers, because the numbers in the random class is random itself. The most important thing is NOT to shuffle in the random number array BUT to get different startpoints in the random array.

So i think my solution is pretty good... i think the Random Class is misunderstood. Dont shuffle but get different starting points because the numbers NEXT to your starting poits IS random for your application.

by Risto Karhu on Friday, January 16th 2009 at 05:45 AM

Ok...saw that now. The default constructor Takes the system time as seed.

Thats ok then. Cant see the point to shuffle .. just create the Random class with def constructor and go on with Random.next.

by Piotr on Friday, January 16th 2009 at 07:55 AM

Question to Risto Karhu:

so

Random r1 = new Random();
Random r2 = new Random();

r1.NextDouble() will give the same as r2.NextDouble()

-----
Random r1 = new Random();
double first r1.NextDouble();
double second r1.NextDouble();

first and second will give different results
?????

by Ravi Wallau on Friday, February 6th 2009 at 10:52 PM

This article has changed since I wrote my first comment a while ago, the method GetNextRandom() was removed from the code sample, which invalidates my comment in the top of this thread.

The article at MSDN provides valuable information about this: http://msdn.microsoft.com/en-us/library/system.random.aspx

Piotr, the Random class, when constructed using the default constructor (no parameters), create a random object using the default constructor that uses the system time. As the code is executed very fast, both instances are seeded with the same value, therefore generating the same sequence numbers. But if you use the same object to generate two numbers in sequence, then you will have different results.

The pseudo-random numbers (they are not truly random as they are algorithm-based, algorithm that is initialized with a number) can be used in this way when you need random numbers to build a geme or something similar. The one thing to keep in mind is that someone VERY interested in breaking on your application may guess the next random number generated by it, if he/ she knows a number of previous random numbers.

For example, if a person knows that you used the default Random constructor and that it's constructed, let's say, when the application starts, then he/ she could initialize many random classes with all the possible seeds for the past, let's say, 30 minutes, and cross that information with the numbers that your application has constructed until he/ she finds the right sequence of numbers. With that information, one could certainly guess what would be the next generated random number.

by yvisek on Saturday, March 21st 2009 at 06:22 PM

Well, when you need "realy" random numbers, you should check this: http://random.org/

cu!

by Vinod Kumar Sahu on Monday, March 30th 2009 at 01:47 AM

I get well help using this code. thanks for giving the code for random function.

by Vinod Kumar Sahu on Monday, March 30th 2009 at 01:48 AM

I get well help using this code. thanks for giving the code for random function.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials

Random Number Generation

On Sunday, April 25th 2004 at 01:54 PM by Sean Eshbaugh in C

Random number within a range

On Tuesday, March 16th 2004 at 06:53 PM by Andrew Pociu in C++


Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons