egolop.blogg.se

Best random number generator algorithm
Best random number generator algorithm






When you fill in the values and click Generate, the program generates random numbers and displays histograms showing their distribution. It returns an integer between a lower bound (inclusive) and an upper bound (exclusive). This matches the behavior provided by the Random class’s Next method. The code then uses the (int) cast operator to truncate the result to get an integer. The final result is a value between min and max, not including max. (This is why I didn’t want scale to be uint.MaxValue–so the result of this division would be less than 1.0.) It multiplies this value by the difference between the maximum and minimum desired values and adds the result to the minimum value. This produces a value between 0.0 and 1.0, not including 1.0. The code then divides scale by the uint.MaxValue. (It is extremely unlikely that scale will be uint.MaxValue and much less likely that this will happen twice in a row so the loop won’t last long.) If scale is still uint.MaxValue, then the loop repeats until it gets a new value. If the bytes span all of the possible byte values (and they should), then the unsigned integer spans all possible unsigned integer values. It then uses BitConverter.ToUInt32 to convert those four bytes into a four-byte unsigned integer ( int) and sets scale equal to that value. Inside the loop, the method uses the RNGCryptoServiceProvider to generate four bytes. I don’t want the method to use that value for scale (you’ll see why in a moment) so the method enters a while loop that executes as long as scale is uint.MaxValue. The RandomInteger method starts by setting the value scale to uint.MaxValue. It’s up to you to convert those bytes into whatever values you need. The RandomInteger method uses that object to generate random numbers.Īll the RNGCryptoServiceProvider does is generate bytes. Add min to the scaled difference between max and min.Īt the class level, the program creates the RNGCryptoServiceProvider. Scale = BitConverter.ToUInt32(four_bytes, 0) Private int RandomInteger(int min, int max) Return a random integer between a min and max value.

best random number generator algorithm

(RNG stands for Random Number Generator.) The following code shows the RandomInteger method that generates random integers between an upper and lower bound. This example uses a RNGCryptoServiceProvider to generate random numbers. What does “cryptographically secure” mean? It means that an attacker, after seeing a series of random numbers that you generate, cannot predict the next one with any success. The Random class generates random numbers, but they aren’t cryptographically secure.








Best random number generator algorithm