Better random function for C#
11,900
See System.Security.Cryptography.RandomNumberGenerator
Author by
Ivan
Updated on June 06, 2022Comments
-
Ivan almost 2 years
I'm generating many random numbers and I need a good function, since this doesn't help much:
public static class Randomizer { static Random random = new Random((int)DateTime.Now.Ticks); public static int RandomInteger(int minimum, int maximum) { return random.Next(minimum, maximum + 1); } public static double RandomDouble() { return random.NextDouble(); } }
When I use this class, my numbers are very often the same. Do you have any simple idea how I can improve performance of the randomizer?
Thanks, Ivan
-
Arpit Arya over 13 yearsSince the random field in the class is static, it's only instantiated once.
-
abatishchev over 13 yearsHe don't create
new Random()
every call -- or he edited the question -
BrokenGlass over 13 yearsNo he's not -
static Random random
is only initialized once - where is he re-creating it? -
dampee over 13 yearsTrue, or initiate "Random" in the methods like this: int randomInt = (new Random()).Next(min, max);
-
user541686 over 13 yearsClick the link again. :) (Ever noticed the "Other Versions" dropdown?)
-
BrokenGlass over 13 years@dampee it should be only initialized once, it's a common mistake to do exactly what you just suggested, in that case you will get duplicate numbers.
-
Ivan over 13 yearsThanks a lot. Can you just tell me how to generate then a random number? I don't really manage to get what I want..
-
user541686 over 13 yearsUse
RandomNumberGenerator.Create
to instantiate it, and then callGetBytes
on the instance each time to fill an array of bytes. Then try usingBitConverter
's methods to convert it to an integer. -
dampee over 13 years@BrokenGlass. I posted my previous comment at the same time as yours. You are completely right! Looked it up on MSDN. (msdn.microsoft.com/en-us/library/system.random.aspx) Quote: Because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers.
-
Henk Holterman over 13 yearsThis will make it a lot slower, and more secure. But will it give better 'randomness'?
-
David Waters over 13 yearsThe only noticeable difference from the OP is locking for thread safety assuming OP is in a single threaded environment (big assumption) there will not be any difference.
-
user541686 over 13 yearsIt's "secure" precisely because of better randomness.
-
Henk Holterman over 13 yearsNot when you use it wrong. I just meant the OP should have answered some of the comments instead of accepting this.
-
user541686 over 13 years@Henk: I agree -- I think the problem lied somewhere else. I answered his question, but I'm not sure if it's the solution that actually solved his problem.