473,602 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
+ 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 5900

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.ne t
Sep 4 '06 #7

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

Similar topics

28
3675
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 appreciated.
4
13099
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 numbers
23
4168
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 initialize it with the same parameter. Can this be done with JavaScript? I couldn't find anything in the documentation. Basically, what I want to achieve is to obtain always the same sequence of random numbers for the same given initialization...
70
6223
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 using the high-order bits returned by rand() instead of the low-order bits, avoiding using rand() for anything that wants decently random numbers, not using rand() if you want more than approx. UINT_MAX total different sequences, and so on. So I...
16
12063
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 numbers using asp.net? I know about the random namespace within .net, but I need a reference to some code that do the similar stated function above. Plus If you have any coding practice ideas for the above defined project please share them.
104
5110
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 better way than to fill an array of range 0... RAND_MAX with pre-computed primes and using the output of rand() to index into it to extract a random prime.
13
3181
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, with it's massive period of 2^19937-1. Will you only ever have access to a tiny portion of this ring of numbers, if you only use a 32-bit seed? Will this set of sequences be confined to the beginning of the period, ie, your sequence will have to...
3
4672
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 Random((int)_seedTimer.ElapsedTicks); _random = new Random(randomSeed.Next(0,99999999)); return random.Next(min, max);
8
3905
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 Random((int)_seedTimer.ElapsedTicks); _random = new Random(randomSeed.Next(0,99999999)); return random.Next(min, max);
0
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8404
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8054
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8268
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6730
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5867
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1254
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.