473,479 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Generating random seeds for simulation

Hello all,
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.

But for confidence in my results i ran it using a script in a loop.

Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.

Is there a better way of seeding the random number generator in c/c++
than time(NULL).

PS: I did some search and found this small snippet on this group: but i
am not
convinced that it will still result in much different seeds if the
value returned by time(NULL) is the same... any comments?

#include <limits.h>
#include <stdlib.h>
#include <time.h>

void randomize(void)
{
time_t timeval = time(NULL);
unsigned char *ptr = (unsigned char *)&timeval;
unsigned seed = 0;
size_t i;

for (i = 0; i < sizeof timeval; i++)
seed = seed * (UCHAR_MAX+2U) + ptr[i];

srand(seed);

}

Aug 25 '06 #1
6 5889

I tired many things to avoid the duplications but in vain.
But I have one suggestion for you, use this "timeval" value as seed and
generated the random numbers using this ( i am sure there will not any
duplication) and use the generated random numbers as the seed to your
function.

This may solve your problem.

Aug 25 '06 #2
Intiha wrote:
Hello all,
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.

But for confidence in my results i ran it using a script in a loop.

Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.

Is there a better way of seeding the random number generator in c/c++
than time(NULL).

PS: I did some search and found this small snippet on this group: but i
am not
convinced that it will still result in much different seeds if the
value returned by time(NULL) is the same... any comments?
Som platforms might provide apis for other things that varies
between invocations such as a process id.
Or, if the program is run sequentially, you read a number to
use as a seed from a file at startup, increment it and write it back to
the file.
Other possibilities is to pass part of a seed as an argument, where the
seed is provided by some platform specific way.
Aug 25 '06 #3
Intiha wrote:
Hello all,
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.

But for confidence in my results i ran it using a script in a loop.

Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.

Is there a better way of seeding the random number generator in c/c++
than time(NULL).
If you want different outputs, you need different inputs.

In your case, I'd suggest modifying your script so that it
provides a different command-line argument to your program each
time around the loop: "myprog 1", "myprog 2", ... Hash this
value with the time() result so the srand() argument will be
different even if time() doesn't change from one run to the
next. Note that the hash should not be something simple like
`time(NULL) ^ cmdarg', because a small change in time() could
be cancelled by a small change in cmdarg -- do something more
"pervasive," like using cmdarg as the initial value of `seed'
in the randomize() function you quoted.

Some systems provide sources of "truly random" (whatever
that means) numbers, often through a special file name like
/dev/random. These sources are usually slow and hence not a
substitute for rand(), but they provide a good way to get an
srand() argument that's suitably unpredictable. Unfortunately,
such things are not part of C itself, and they way they're
provided (if they're provided) varies from system to system.
Consult your documentation.

Finally, I note that if time() returns the same value at
the start of "many" runs, then your simulation program probably
doesn't run very long. Instead of running the whole program
over and over, struggling with ways to get different srand()
seeds each time, consider rearranging your program so it runs
many simulations each time it executes. Call srand() once at
the beginning of this "super-program," and then just let the
repeated "internal" simulations keep on calling rand().

Old:

int main(void) {
srand(...);
simulate();
return 0;
}

New:

int main(void) {
int run;
srand(...);
for (run = 0; run < 100; ++run)
simulate();
return 0;
}

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 25 '06 #4
Intiha wrote:
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.

But for confidence in my results i ran it using a script in a loop.

Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.

Is there a better way of seeding the random number generator in c/c++
than time(NULL).

PS: I did some search and found this small snippet on this group: but i
am not
convinced that it will still result in much different seeds if the
value returned by time(NULL) is the same... any comments?

#include <limits.h>
#include <stdlib.h>
#include <time.h>

void randomize(void)
{
time_t timeval = time(NULL);
unsigned char *ptr = (unsigned char *)&timeval;
unsigned seed = 0;
size_t i;

for (i = 0; i < sizeof timeval; i++)
seed = seed * (UCHAR_MAX+2U) + ptr[i];

srand(seed);
}
That's not seriously any different from just setting the seed to
time(NULL) in terms of variability. Let's try this:

#include <limits.h>
#include <stdlib.h>
#include <time.h>

static struct {
clock_t c;
time_t t;
int counter;
} entropy = { (clock_t) 0, (time_t) 0, 0 };
static unsigned char * p = (unsigned char *) (&entropy + 1);
static int accSeed = 0;

void randomize (void) {
if (p == ((unsigned char *) (&entropy + 1))) {
entropy.c += clock();
entropy.t += time (NULL);
entropy.counter++;
p = (unsigned char *) &entropy.c;
}
accSeed = ((accSeed * (UCHAR_MAX+2U)) | 1) + (int) *p;
p++;
srand (accSeed);
}

So we are taking 3 sources of entropy, time(NULL), clock() and a simple
incrementing counter. On most 32-bit systems, it will take 12 times
through the randomize() function before it fetches more entropy. Even
if your benchmark takes 0 time, the seed should at least wander through
a pseudo random sequence of numbers, so that you can expect somewhat
different seeding over time.

Obviously you can add platform specific entries to the entropy
structure that reflects more entropic information such as process-ID or
RDTSC on Intel platforms, etc.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Aug 25 '06 #5
thats one of the ideas that i had. Unfortunately I didnt want to worry
about resetting of the simulation objects before I worried about it.

What i am doing currently (and this certainly fixes the issue as well)
is using a perl scrip to call my program , with the program taking
input a seed.
Now this seed i am generating from the perl scrip that is srand'ed with
time().
This is giving me exactly what you are suggesting without the worry of
simulation clean up (that i know i have to do .. but didnt have time :)

Thank you All.
Eric Sosman wrote:
Intiha wrote:
Hello all,
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.

But for confidence in my results i ran it using a script in a loop.

Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.

Is there a better way of seeding the random number generator in c/c++
than time(NULL).

If you want different outputs, you need different inputs.

In your case, I'd suggest modifying your script so that it
provides a different command-line argument to your program each
time around the loop: "myprog 1", "myprog 2", ... Hash this
value with the time() result so the srand() argument will be
different even if time() doesn't change from one run to the
next. Note that the hash should not be something simple like
`time(NULL) ^ cmdarg', because a small change in time() could
be cancelled by a small change in cmdarg -- do something more
"pervasive," like using cmdarg as the initial value of `seed'
in the randomize() function you quoted.

Some systems provide sources of "truly random" (whatever
that means) numbers, often through a special file name like
/dev/random. These sources are usually slow and hence not a
substitute for rand(), but they provide a good way to get an
srand() argument that's suitably unpredictable. Unfortunately,
such things are not part of C itself, and they way they're
provided (if they're provided) varies from system to system.
Consult your documentation.

Finally, I note that if time() returns the same value at
the start of "many" runs, then your simulation program probably
doesn't run very long. Instead of running the whole program
over and over, struggling with ways to get different srand()
seeds each time, consider rearranging your program so it runs
many simulations each time it executes. Call srand() once at
the beginning of this "super-program," and then just let the
repeated "internal" simulations keep on calling rand().

Old:

int main(void) {
srand(...);
simulate();
return 0;
}

New:

int main(void) {
int run;
srand(...);
for (run = 0; run < 100; ++run)
simulate();
return 0;
}

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 27 '06 #6
On 25 Aug 2006 05:41:42 -0700, we******@gmail.com wrote:
Intiha wrote:
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.

But for confidence in my results i ran it using a script in a loop.

Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.
<snip: hashing value of time()>
That's not seriously any different from just setting the seed to
time(NULL) in terms of variability. Let's try this:
That's true.
static struct {
clock_t c;
time_t t;
int counter;
} entropy = { (clock_t) 0, (time_t) 0, 0 };
static unsigned char * p = (unsigned char *) (&entropy + 1);
static int accSeed = 0;
Minor point: accSeed doesn't need to be file-scope; it doesn't
remember anything from one call to the next. Even more minor: the
initializers for the struct don't need to be cast and don't even need
to be given at all, although they do provide some documentation and/or
confirmation that you really wanted (needed) the default effect.
void randomize (void) {
if (p == ((unsigned char *) (&entropy + 1))) {
entropy.c += clock();
entropy.t += time (NULL);
entropy.counter++;
p = (unsigned char *) &entropy.c;
}
accSeed = ((accSeed * (UCHAR_MAX+2U)) | 1) + (int) *p;
p++;
srand (accSeed);
}

So we are taking 3 sources of entropy, time(NULL), clock() and a simple
incrementing counter. On most 32-bit systems, it will take 12 times
Not in the situation the OP gave of rerunning the program.
clock() is supposed to reflect the CPU time used _by this execution of
this program_ (i.e. by this process); if called near program startup,
as a randomize function usually should be, it will usually be near
zero. 'counter' is initialized to zero on each program execution and
will always be the same value, 1, on the first call.
through the randomize() function before it fetches more entropy. Even
if your benchmark takes 0 time, the seed should at least wander through
a pseudo random sequence of numbers, so that you can expect somewhat
different seeding over time.

Obviously you can add platform specific entries to the entropy
structure that reflects more entropic information such as process-ID or
RDTSC on Intel platforms, etc.
On most popular OSen for processes run in quick succession, processID
doesn't add _much_ entropy (this was actually partially responsible
for a break of an early implementation of SSL) and a fine(r) clock
like TSC only a modest amount. Although that might have been enough
for the OP, who I see elsethread has instead gone to persisting state
through the invoking script. Another traditional approach in the
program itself is to write out an ending state or value on one run and
read it back it in and use it on the next; this also has the feature
that you can save the seed value(s) if you need (or think you may
need) to recreate some particular run(s).

- David.Thompson1 at worldnet.att.net
Sep 4 '06 #7

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

Similar topics

28
3650
by: Paul Rubin | last post by:
http://www.nightsong.com/phr/python/sharandom.c This is intended to be less predicable/have fewer correlations than the default Mersenne Twister or Wichmann-Hill generators. Comments are...
4
13085
by: mescaline | last post by:
hi, i'm new to C++ could anyone refer me to a good site / good examples of random numbers? in particular including: 1) the commnds to obtain normally and exponenetially distributed r...
23
4148
by: Thomas Mlynarczyk | last post by:
I remember there is a programming language where you can initialize the random number generator, so that it can - if you want - give you the exactly same sequence of random numbers every time you...
70
6166
by: Ben Pfaff | last post by:
One issue that comes up fairly often around here is the poor quality of the pseudo-random number generators supplied with many C implementations. As a result, we have to recommend things like...
16
12047
by: Leon | last post by:
I need a program that generate 5 non-duplicates random number between 1-10 as string values store in an array. Do anybody know of any good books or websites that explain how to generator random...
104
5029
by: fieldfallow | last post by:
Hello all, Is there a function in the standard C library which returns a prime number which is also pseudo-random? Assuming there isn't, as it appears from the docs that I have, is there a...
13
3158
by: porterboy76 | last post by:
If you only use a 32 bit seed for a random number generator, does that mean you can only ever produce a maximum of 2^32 (approx 4 billion) different sequences? What about the Mersenne Twister,...
3
4661
by: Daniel | last post by:
Hey guys Using Random(), how random is it, is it possible to be predicted? I have a requirement for a very good random number generator. I was doing something such as: Random randomSeed = new...
8
3893
by: Daniel | last post by:
Hey guys Using Random(), how random is it, is it possible to be predicted? I have a requirement for a very good random number generator. I was doing something such as: Random randomSeed = new...
0
6899
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7067
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6719
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
6847
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4757
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
2980
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
2970
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1288
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
166
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.