473,385 Members | 1,472 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Trap when using Random() ... make sure it is not being changed tooquickly

For the public record.

RL

public void IterateOne()
{
Random myRandom = new Random(); //declare Random outside
the iteration
for (int j = 0; j < Max; j++)
{
// Random myRandom = new Random(); //don’t declare
Random here since will not give random results if 'for' loop’s too
fast!
}
}

//Declare your random variable once in your program. Any random
declared within the same time slice will have the same seed.
Oct 24 '08 #1
16 2044
Definitely. That is why the documentation for the System.Random()
constructor says: (http://msdn.microsoft.com/en-us/library/h343ddh9.aspx)

The default seed value is derived from the system clock and has finite
resolution. As a result, different Random objects that are created in close
succession by a call to the default constructor will have identical default
seed values and, therefore, will produce identical sets of random numbers.
This problem can be avoided by using a single Random object to generate all
random numbers.
"raylopez99" <ra********@yahoo.comwrote in message
news:bc**********************************@u46g2000 hsc.googlegroups.com...
For the public record.

RL

public void IterateOne()
{
Random myRandom = new Random(); //declare Random outside
the iteration
for (int j = 0; j < Max; j++)
{
// Random myRandom = new Random(); //don’t declare
Random here since will not give random results if 'for' loop’s too
fast!
}
}

//Declare your random variable once in your program. Any random
declared within the same time slice will have the same seed.

Oct 25 '08 #2
Family Tree Mike wrote:
Definitely. That is why the documentation for the System.Random()
constructor says: (http://msdn.microsoft.com/en-us/library/h343ddh9.aspx)

The default seed value is derived from the system clock and has finite
resolution. As a result, different Random objects that are created in
close succession by a call to the default constructor will have
identical default seed values and, therefore, will produce identical
sets of random numbers. This problem can be avoided by using a single
Random object to generate all random numbers.
It is something that is known for all languages and
technologies.

Arne
Oct 26 '08 #3
It is something that is known for all languages and
technologies.
I don't think that is quite accurate :-)

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com
Oct 26 '08 #4
Peter Morris wrote:
>It is something that is known for all languages and
technologies.

I don't think that is quite accurate :-)
I have seen it in C, Fortran, Java, Pascal, ASP/VBS
and PHP.

Arne
Oct 26 '08 #5
On Sun, 26 Oct 2008 02:41:29 -0700, Peter Morris
<mr*********@spamgmail.comwrote:
>It is something that is known for all languages and
technologies.

I don't think that is quite accurate :-)
Well, "all" might be overreaching. But "all broadly used" probably isn't,
especially if one is specifically discussing using the common technique of
seeding a random number generator with some time value, and especially if
we limit the discussion to Windows (where we know in advance the
limitations of retrieving a time value).

All pseudo-random-number generators require a seed, and the two most
common ways to provide that seed are to default to 0 and to use a time
value. In either case, repeatedly creating a new generator is always
wrong; to produce a series of random numbers, one should always initialize
the generator once, and then use the same one repeatedly.

Obviously if the seed is always the same, creating a new generator for
each new random number is wrong. When the seed is 0, that's a trivial
case to demonstrate. But it's also true that on the broadly-used PC
operating systems (including Windows), functions to retrieve the current
time have limited precision and if called too quickly in succession will
actually return the same value.

I think the most important lesson is that a person ought to read the
documentation when using some API. The caveat "FTM" quoted is provided in
multiple places in the documentation for Random, including the main class
page and (as he points out) the page documenting the constructor. Even a
person who wasn't familiar with the general issue would, given that
documentation, be able to learn about the specific caveats regarding the
Random class. Had they bothered to read the documentation, of course.

Which is a very long way of saying that Arne's comment might not have been
literally true, but I doubt that someone can come up with a
counter-example that involves a random-number generator in common use and
it's not like the issue described in this thread should be some sort of
remarkable revelation to anyone.

Pete
Oct 26 '08 #6
On Oct 24, 11:30*pm, raylopez99 <raylope...@yahoo.comwrote:
For the public record.

public void IterateOne()
* * * * {
* * * * * * Random myRandom = new Random(); //declare Random outside
the iteration
* * * * * * for (int j = 0; j < Max; j++)
* * * * * * {
* * * * * * * *// Random myRandom = new Random(); //don’t declare
Random here since will not give random results if 'for' loop’s too
fast!
* * * * * }

}

//Declare your random variable once in your program. *Any random
declared within the same time slice will have the same seed.
However, be careful of the fact that Random isn't thread-safe. That's
why I created the very simple StaticRandom class, which just creates
an instance of Random and makes every access to it sequential. It's
not particularly clever, but it's very useful :)

Jon
Oct 27 '08 #7
On Oct 24, 7:30 pm, raylopez99 <raylope...@yahoo.comwrote:
For the public record.

RL

public void IterateOne()
{
Random myRandom = new Random(); //declare Random outside
the iteration
for (int j = 0; j < Max; j++)
{
// Random myRandom = new Random(); //don’t declare
Random here since will not give random results if 'for' loop’s too
fast!
}

}

//Declare your random variable once in your program. Any random
declared within the same time slice will have the same seed.
You do realize that each time a new iteration is performed a new
instance of Random is create right?
As a component of Random is the time so of course it will ot work as
you expect.
Oct 27 '08 #8
On Oct 27, 7:17*am, "Ignacio Machin ( .NET/ C# MVP )"
<ignacio.mac...@gmail.comwrote:
On Oct 24, 7:30 pm, raylopez99 <raylope...@yahoo.comwrote:
For the public record.
RL
public void IterateOne()
* * * * {
* * * * * * Random myRandom = new Random(); //declare Random outside
the iteration
* * * * * * for (int j = 0; j < Max; j++)
* * * * * * {
* * * * * * * *// Random myRandom = new Random(); //don’t declare
Random here since will not give random results if 'for' loop’s too
fast!
* * * * * }
}
//Declare your random variable once in your program. *Any random
declared within the same time slice will have the same seed.

You do realize that each time a new iteration is performed a new
instance of Random is create right?
As a component of Random is the time so of course it will ot work as
you expect.
Not true. You probably did not notice that I //commented out the
code. The part that works is outside the loop.

Now tell me this: why does MSFT have two different strands of
Random()? One is supposedly more "cryptographically secure" or
robust. Perhaps the more robust version is 64 bits vs. 32 bits, or
something like that.

RL
Oct 28 '08 #9
On Oct 26, 10:13*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
Which is a very long way of saying that Arne's comment might not have been *
literally true, but I doubt that someone can come up with a *
counter-example that involves a random-number generator in common use and*
it's not like the issue described in this thread should be some sort of *
remarkable revelation to anyone.
Nothing in any language is 'remarkable', though pointers, delegates
and LINQ via lambda expressions come close. I am getting the hang of
using LINQ with lambda expressions, and haven't even bought a book on
the subject yet.

I posted this for future reference since Googling this topic only
yielded a hint in one other forum.

Thanks for your understanding.

RL

Oct 28 '08 #10
On Oct 27, 6:07*am, "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
>
//Declare your random variable once in your program. *Any random
declared within the same time slice will have the same seed.

However, be careful of the fact that Random isn't thread-safe. That's
why I created the very simple StaticRandom class, which just creates
an instance of Random and makes every access to it sequential. It's
not particularly clever, but it's very useful :)

Hi,
What is a good book on parallel programming for C#? I have seen bits
and pieces here and there, and have sort of a 10000 m view, but if you
have any favorites please let me know.

RL

Oct 28 '08 #11
raylopez99 <ra********@yahoo.comwrote:
What is a good book on parallel programming for C#? I have seen bits
and pieces here and there, and have sort of a 10000 m view, but if you
have any favorites please let me know.
Coming very soon:

http://www.amazon.com/products/dp/032143482X

It's very, very detailed - be warned! (But wonderful...)

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 28 '08 #12
On Oct 28, 12:52*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
raylopez99 <raylope...@yahoo.comwrote:
What is a good book on parallel programming for C#? *I have seen bits
and pieces here and there, and have sort of a 10000 m view, but if you
have any favorites please let me know.

Coming very soon:

http://www.amazon.com/products/dp/032143482X

It's very, very detailed - be warned! (But wonderful...)

--
Jon Skeet - <sk...@pobox.com>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
Thanks I pre-ordered it.

I hope it's also a tutorial too, not just a reference book.

RL
Oct 29 '08 #13
raylopez99 <ra********@yahoo.comwrote:
Thanks I pre-ordered it.

I hope it's also a tutorial too, not just a reference book.
I'm not sure I'd call it a tutorial as such, but it's far from just a
reference book.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 29 '08 #14
On Oct 29, 9:44*am, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
raylopez99 <raylope...@yahoo.comwrote:
Thanks I pre-ordered it.
I hope it's also a tutorial too, not just a reference book.

I'm not sure I'd call it a tutorial as such, but it's far from just a
reference book.
I hope it's not one of those "philosophical" books that waxes
eloquently about the wonders of parallel programming without actually
showing much. BTW your book on advanced C# 3.0 is borderline like
this--it talks a lot about the history and evolution of C#3 from #2,
#1--which is OK but not really what I am looking for when learning the
language (after I've mastered it, it's another story). But your book
is useful and I'm reading it slowly everyday--your Appendix A on Linq,
like you've said, is very good. It's just now a keeper compared to,
say, Albahari et al's C# book, which is amazingly packed with
information. Still, for $20 bucks what you do expect? It's better
than nothing. I usually keep only half the books I buy--the rest I
read once and trash. I like your publisher's decision to make the
book available in keyword searchable PDF format, which means I can
index it using Google desktop and refer to key phrases later on.

RL
Oct 29 '08 #15
raylopez99 <ra********@yahoo.comwrote:
I hope it's also a tutorial too, not just a reference book.
I'm not sure I'd call it a tutorial as such, but it's far from just a
reference book.

I hope it's not one of those "philosophical" books that waxes
eloquently about the wonders of parallel programming without actually
showing much.
No, definitely not. You'll see a *lot* of detail.
BTW your book on advanced C# 3.0 is borderline like
this--it talks a lot about the history and evolution of C#3 from #2,
#1--which is OK but not really what I am looking for when learning the
language (after I've mastered it, it's another story). But your book
is useful and I'm reading it slowly everyday--your Appendix A on Linq,
like you've said, is very good. It's just now a keeper compared to,
say, Albahari et al's C# book, which is amazingly packed with
information. Still, for $20 bucks what you do expect? It's better
than nothing. I usually keep only half the books I buy--the rest I
read once and trash. I like your publisher's decision to make the
book available in keyword searchable PDF format, which means I can
index it using Google desktop and refer to key phrases later on.
Well, I'm glad you like Nutshell - so do I.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Nov 1 '08 #16
Jon Skeet [ C# MVP ] wrote:
>
Well, I'm glad you like Nutshell - so do I.
Yes, it's quite good. Every book has it's place. Some, like yours, I
read once to learn (though I have ripped out the Appendix A which I
use as a cheat sheet for Linq). Others, like Albahari's Nutshell, I
refer to daily. Others, like the receipe book and Judith Bishop's
Gang of Four design templates for C# book, you read once in a blue
moon just for solving a specific problem. Then you have specialty
books like that fat one on Linq that you reviewed recently--just to
drill down more. It's all good and cheap--where else can you get
expert instruction for just $20 or so? Even your colleagues cannot be
bothered for that cheap I would wager (plus you don't want to ask
them, since it might look like you don't know what you're doing).

I like this board too--a very good resource.

Back to coding....(I'm doing some graphics stuff ...which is full of
tricks....I'm developing a board game...)

RL
Nov 1 '08 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

31
by: lawrence | last post by:
I'm not sure how this is normally done, on a large site, perhaps one running Phorum. Occassionally a thread will have hundreds of entries, perhaps a meg or two worth of data. You won't necessarily...
6
by: Terry Bell | last post by:
We've had a very large A97 app running fine for the last seven years. I've just converted to SQL Server backend, which is being tested, but meanwhile the JET based version, running under terminal...
11
by: pemo | last post by:
Ambiguous? I have a student who's asked me to explain the following std text (esp. the footnote). 6.2.6.1.5 Certain object representations need not represent a value of the object type. If...
10
by: pemo | last post by:
As far as I understand it, a trap representation means something like - an uninitialised automatic variable might /implicitly/ hold a bit-pattern that, if read, *might* cause a 'trap' (I'm not...
4
by: Christina | last post by:
A project I am working on requires 5 random popup windows that rotate. A cookie is set each time one of the popups occurs with a 5 day expire period. The visitor isn't supposed to see the same...
1
by: pigeonrandle | last post by:
Hi, I thought i should give a better explanation to my second 'bug' in my previous post (Bugs in VS2003 SP1) because it's taken me ages to figure out what was going on. Basically, one of my...
17
by: Army1987 | last post by:
If uMyInt_t is an unsigned integral type, is the following a necessary and sufficient condition that uMyInt_t has no trap representation? (uMyInt_t)(-1) >CHAR_BIT*sizeof(uMyInt_t)-1 That is,...
39
by: Alan Isaac | last post by:
This may seem very strange, but it is true. If I delete a .pyc file, my program executes with a different state! In a single directory I have module1 and module2. module1 imports random and...
94
by: Samuel R. Neff | last post by:
When is it appropriate to use "volatile" keyword? The docs simply state: " The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.