.NET random number generator visit.

I have a pseudo random number generator (PRNG) with good properties that uses six UInt32

as a state. I need to come up with a sane way to seed it. Two obvious possibilities: 1) generate six random numbers using System.Random

and use them as seeds; 2) generate two GUID

s Guid.NewGuid()

. What would be better?

I don't need cryptographic security.

+1


source to share


4 answers


If he needs it UInt32

, is it Random

more convenient? just Next()

, Next()

, Next()

etc. (and casting) ... (use the same instance Random

, however - don't create new Random()

every time).



It depends on what the intent is, whether it has enough randomness. Since this is just a seed, it should be fine ...

+4


source


Unfortunately System.Random () also requires an initial value. By default, the current tick counter is used, which is predictable and in fact not random. Therefore, you will need the seed for Random, which will lead you to your original question ...



I've never used Guid.GetHashCode () as a seed before, but my second reaction is that doesn't seem like a bad idea.

+4


source


Do you need cryptographic security, why not just use System.Security.Cryptography.RNGCryptoServiceProvider to generate your random numbers? Unless there is a specific reason, like being too slow, I don't understand why you didn't use it. Since it is a cryptographic random generator, you will get much better random numbers and don't have to worry about seeding it.

+4


source


Try this for your seed value ...

(UInt32)Math.Pow(System.DateTime.Now.TimeOfDay.TotalMilliseconds, 11.0 / 7.0)

      

It just increases the current milliseconds to 11 / 7th power, which is just arbitrary. You can experiment with other factions to make sure they work best for you.

Beware that if the decimal equivalent of your fraction is greater than about 2.5, you may get overflow and your initial value will be zero. :(

I've been using this for a while and it seems to give pretty good seed values.

0


source







All Articles