How do I generate a random int number?

前端 未结 30 2596
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

30条回答
  •  日久生厌
    2020-11-21 11:55

    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

提交回复
热议问题