DateTime.Now Millisecond is always 0

G

Guest

I am writing some simple games using the Compact Framework and I'm trying to
get better random numbers. I've been using DateTime.Now to get the
Millisecond field to seed the random number generator, but the value is
always 0 (both in the emulator and on my Pocket PC). I started using
Environment.TickCount, but values don't vary as much as I would like.

I've download several different code samples to improve the randomness, but
it seems that if the initial seed isn't random enough, it won't matter much.

If anyone has any suggestions, I'd appreciate it.
 
P

Peter Foot [MVP]

You could always look at using the Crypto APIs for better random number
generation - see the wrappers in the OpenNETCF Smart Device Framework -
www.opennetcf.org/sdf/ e.g.
OpenNETCF.Security.Cryptography.RandomNumberGenerator

Peter
 
G

Guest

What I'm looking for is not how to generate a random number, it's how do I
better seed the random number generator itself. There is a parameter that
can be passed in to the Random constructor that allows you to seed the random
number generator yourself, rather than having the Compact Framework do it for
you.

Instead of this:
Random rnd = new Random();
You do this:
Random rnd = new Random( SomeInteger );

The values I'm getting from the framework's Random object just aren't random
enough.

Rich
 
P

Paul G. Tobey [eMVP]

You could use the result of calling GetTickCount(). That's the number of ms
since the unit booted. Obviously, it's going to be biased toward the lower
end of the DWORD range, but you might shift the bytes around or something to
address that.

Paul T.
 
D

Dick Grier

Hi,

This is a standard problem (Donald Knuth addressed it, in more general terms
about 30 years ago).

I think a reasonable approach is to extend Paul's suggestion by using Random
to extract an integer sized "chunk" from the value returned by GetTickCount
(or what I use, which is Now.Ticks.ToString) -- cast this to an integer AND
THEN use this value to seed the "real" Random function.

Dick

--
Richard Grier (Microsoft Visual Basic MVP)

See www.hardandsoftware.net for contact information.

Author of Visual Basic Programmer's Guide to Serial Communications, 4th
Edition ISBN 1-890422-28-2 (391 pages) published July 2004. See
www.mabry.com/vbpgser4 to order.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top