How do I generate a random integer in C#?
While this is okay:
Random random = new Random();
int randomNumber = random.Next()
You'd want to control the limit (min and max mumbers) most of the time. So you need to specify where the random number starts and ends.
The Next()
method accepts two parameters, min and max.
So if i want my random number to be between say 5 and 15, I'd just do
int randomNumber = random.Next(5, 16)
Random rand = new Random();
int name = rand.Next()
Put whatever values you want in the second parentheses make sure you have set a name by writing prop and double tab to generate the code
The question looks very simple but the answer is bit complicated. If you see almost everyone has suggested to use the Random class and some have suggested to use the RNG crypto class. But then when to choose what.
For that we need to first understand the term RANDOMNESS and the philosophy behind it.
I would encourage you to watch this video which goes in depth in the philosophy of RANDOMNESS using C# https://www.youtube.com/watch?v=tCYxc-2-3fY
First thing let us understand the philosophy of RANDOMNESS. When we tell a person to choose between RED, GREEN and YELLOW what happens internally. What makes a person choose RED or YELLOW or GREEN?
Some initial thought goes into the persons mind which decides his choice, it can be favorite color , lucky color and so on. In other words some initial trigger which we term in RANDOM as SEED.This SEED is the beginning point, the trigger which instigates him to select the RANDOM value.
Now if a SEED is easy to guess then those kind of random numbers are termed as PSEUDO and when a seed is difficult to guess those random numbers are termed SECURED random numbers.
For example a person chooses is color depending on weather and sound combination then it would be difficult to guess the initial seed.
Now let me make an important statement:-
*“Random” class generates only PSEUDO random number and to generate SECURE random number we need to use “RNGCryptoServiceProvider” class.
Random class takes seed values from your CPU clock which is very much predictable. So in other words RANDOM class of C# generates pseudo random numbers , below is the code for the same.
var random = new Random();
int randomnumber = random.Next()
While the RNGCryptoServiceProvider
class uses OS entropy to generate seeds. OS entropy is a random value which is generated using sound, mouse click, and keyboard timings, thermal temp etc. Below goes the code for the same.
using (RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider())
{
byte[] rno = new byte[5];
rg.GetBytes(rno);
int randomvalue = BitConverter.ToInt32(rno, 0);
}
To understand OS entropy see this video from 14:30 https://www.youtube.com/watch?v=tCYxc-2-3fY where the logic of OS entropy is explained. So putting in simple words RNG Crypto generates SECURE random numbers.
Every time you do new Random() it is initialized . This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.
//Function to get random number
private static readonly Random getrandom = new Random();
public static int GetRandomNumber(int min, int max)
{
lock(getrandom) // synchronize
{
return getrandom.Next(min, max);
}
}
This is the class I use. Works like RandomNumber.GenerateRandom(1, 666)
internal static class RandomNumber
{
private static Random r = new Random();
private static object l = new object();
private static Random globalRandom = new Random();
[ThreadStatic]
private static Random localRandom;
public static int GenerateNewRandom(int min, int max)
{
return new Random().Next(min, max);
}
public static int GenerateLockedRandom(int min, int max)
{
int result;
lock (RandomNumber.l)
{
result = RandomNumber.r.Next(min, max);
}
return result;
}
public static int GenerateRandom(int min, int max)
{
Random random = RandomNumber.localRandom;
if (random == null)
{
int seed;
lock (RandomNumber.globalRandom)
{
seed = RandomNumber.globalRandom.Next();
}
random = (RandomNumber.localRandom = new Random(seed));
}
return random.Next(min, max);
}
}
I will assume that you want a uniformly distributed random number generator like below. Random number in most of programming language including C# and C++ is not properly shuffled before using them. This means that you will get the same number over and over, which isn't really random. To avoid to draw the same number over and over, you need a seed. Typically, ticks in time is ok for this task. Remember that you will get the same number over and over if you are using the same seed every time. So try to use varying seed always. Time is a good source for seed because they chage always.
int GetRandomNumber(int min, int max)
{
Random rand = new Random((int)DateTime.Now.Ticks);
return rand.Next(min, max);
}
if you are looking for random number generator for normal distribution, you might use a Box-Muller transformation. Check the answer by yoyoyoyosef in Random Gaussian Variable Question. Since you want integer, you have to cast double value to integer at the end.
Random rand = new Random(); //reuse this if you are generating many
double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0-rand.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal =
mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)
Random Gaussian Variables