How do you generate a random number in C#?

前端 未结 6 1761
天命终不由人
天命终不由人 2020-12-25 12:34

I would like to generate a random floating point number between 2 values. What is the best way to do this in C#?

相关标签:
6条回答
  • 2020-12-25 12:55

    For an explaination of why Longhorn has been downmodded so much: http://msdn.microsoft.com/en-us/magazine/cc163367.aspx Look for the implementation of NextDouble and the explanation of what is a random double.

    That link is also a goo example of how to use cryptographic random numbers (like Sameer mentioned) only with actual useful outputs instead of a bit stream.

    0 讨论(0)
  • 2020-12-25 12:59
    // generate a random number starting with 5 and less than 15
    Random r = new Random();
    int num = r.Next(5, 15);  
    

    For doubles you can replace Next with NextDouble

    0 讨论(0)
  • 2020-12-25 12:59

    Here is a snippet of how to get Cryographically safe random numbers: This will fill in the 8 bytes with a crytographically strong sequence of random values.

    byte[] salt = new byte[8];
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    rng.GetBytes(salt);
    

    For more details see How Random is your Random??" (inspired by a CodingHorror article on deck shuffling)

    0 讨论(0)
  • 2020-12-25 13:00

    The only thing I'd add to Eric's response is an explanation; I feel that knowledge of why code works is better than knowing what code works.

    The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). NextDouble only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and range.

    So, this would give us random doubles between 0.0 and 2.0:

    rng.NextDouble() * 2.0

    But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:

    2.5 + rng.NextDouble() * 2.0

    Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.

    At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:

    double NextDouble(Random rng, double min, double max)
    {
        return min + (rng.NextDouble() * (max - min));
    }
    0 讨论(0)
  • 2020-12-25 13:05
    System.Random r = new System.Random();
    
    double rnd( double a, double b )
    {
       return a + r.NextDouble()*(b-a);
    }
    
    0 讨论(0)
  • 2020-12-25 13:06

    How random? If you can deal with pseudo-random then simply:

    Random randNum = new Random();
    randNum. NextDouble(Min, Max);
    

    If you want a "better" random number, then you probably should look at the Mersenne Twister algorithm. Plenty of people hav already implemented it for you though

    0 讨论(0)
提交回复
热议问题