Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Random none too random when called in quick succession

Status
Not open for further replies.

StevenK

Programmer
Jan 5, 2001
1,294
0
0
GB
I'm making use of the 'Randomize' and 'Random()' calls.
However due to the nature of my code (generating a random number as part of a finite looping) the number returned appears to be constant.
If I loop for 10 iterations then the value returned by the 'Random' call is pretty constant.
If I extend the loop to something like 100 then I get similar blocks, ie. the first 20 returns are the same, the 21st differs but then matches returns 22 through 40, etc.
Reviewing the Delphi help files it indicates that the Random function makes use of a value obtained from the system clock - clearly this will remain pretty much a constant on a high-spec machine doing a dozen swift iterations.
How can I best work around this such that I get a truly random return value for each iteration in the loop ?
Any help would be appreciated.
Thanks in advance
Steve
 
try putting Sleep(1); into your loop, it freezes the loop then for 1 millisecond, giving the system clock time to change. [bobafett] BobbaFet [bobafett]

Everyone has a right to my opinion.
E-mail me at caswegkamp@hotmail.com
 
I've had to make use of an additional Randomize / Random call in order to generate a random number to Sleep for a set number of milliseconds and then get the random number I want to use.
Steve
 
Ramdomize causes the ramdom function to be 'seeded' with the time, thus generating a seemingly random number.

The problem with SLEEPing for 1 millisecond is that the system time isn't rounded to the nearest millisecond, it's rounded to the nearest 3 and a bit, such that the time in milliseconds will always end in a 0, 3, or 7. (At least I think it's those values).

If you sleep for 5 milliseconds you should get the effect you're after.
 
There are a lot of posts on the borland.public boards that suggest calling randomize only once in your program, and that the program will use every number only once until all possibilites are exhausted. Brian
"There are 2 kinds of people in the world, those that divide people into two groups and those that don't. I belong to the second group." - tag line I stole
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top