468,736 Members | 2,119 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,736 developers. It's quick & easy.

Way for computing random primes in standard C.

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.

Also what is meant by reinitialising the rand() function with srand(1)?
Does it mean that further calls to rand() will return numbers with a new
starting point? If so, how is it different to calling srand() with a
seed value such as that returned by the time() function?

Thank you all for the help. I find this group very useful.
Feb 24 '06
104 4474
Ben Bacarisse <be********@bsb.me.uk> writes:
On Mon, 27 Feb 2006 21:19:19 -0800, websnarf wrote:

[...]
As one final comment -- using the ANSI C's rand() is bad because the
state size is so small


I don't think the standard mandates any state size, does it? I don't
think there is nothing to stop rand() being a very high quality generator.


Right, but in practice, the common wisdom is that rand() is only
barely adequate, so programs that need high-quality random numbers
don't use it anyway, so there's little motivation for implementers to
improve it.

Also, the standard provides a sample implementation, and many
implementers just use that.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 28 '06 #51
"me********@aol.com" <me********@aol.com> writes:
Walter Roberson wrote:
In article <11*********************@t39g2000cwt.googlegroups. com>,
me********@aol.com <me********@aol.com> wrote:
When it's stated that
"...the Mersenne Twister as the core generator.
It produces 53-bit precision floats and has a period of 2**19937-1."

Doesn't it mean that there are 2**19937-1 states and if one were
to actually call it 2**19937 times, then one would be right back
where one started regardless of what number srand() was called with?


Not necessarily.


Then what does "period" mean?


It means that at some point, it will start over again from the
beginning.

Consider a really dumb PNRG that only ever has a cycle of four
different outputs. Perhaps srand(1) will result in the sequence:

1 6 3 12 1 6 3 12 ...

And srand(2) results in:

4 9 5 3 4 9 5 3 ...

note that they both have a period of four, but the values that are
cycled are completely different.
Feb 28 '06 #52
Micah Cowan <mi***@cowan.name> writes:
[...]
It means that at some point, it will start over again from the
beginning.

Consider a really dumb PNRG that only ever has a cycle of four
different outputs. Perhaps srand(1) will result in the sequence:

1 6 3 12 1 6 3 12 ...

And srand(2) results in:

4 9 5 3 4 9 5 3 ...

note that they both have a period of four, but the values that are
cycled are completely different.


The random number generator has at least 8 distinct states (3 bits),
which means it *could* have a cycle of 8 outputs, making full use of
its internal state. For example, srand(1) might result in:

1 6 3 12 4 9 5 3 1 6 3 12 4 9 5 3

and srand(2) might result in:

4 9 5 3 1 6 3 12 4 9 5 3 1 6 3 12

But, as you said, it's a really dumb RNG. Generally speaking, using
only a subset of the available state for a given sequence is allowed
by the standard, but *probably* not a good idea (unless the state is
large enough that a subset of it gives you a very long repeating cycle
anyway).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 28 '06 #53

Micah Cowan wrote:
"me********@aol.com" <me********@aol.com> writes:
Walter Roberson wrote:
In article <11*********************@t39g2000cwt.googlegroups. com>,
me********@aol.com <me********@aol.com> wrote:

>When it's stated that
> "...the Mersenne Twister as the core generator.
> It produces 53-bit precision floats and has a period of 2**19937-1."

>Doesn't it mean that there are 2**19937-1 states and if one were
>to actually call it 2**19937 times, then one would be right back
>where one started regardless of what number srand() was called with?

Not necessarily.
Then what does "period" mean?


It means that at some point, it will start over again from the
beginning.


Isn't that what I said? The issue HERE is how can a periodic
function NOT return eventually to where it started?

Consider a really dumb PNRG that only ever has a cycle of four
different outputs. Perhaps srand(1) will result in the sequence:

1 6 3 12 1 6 3 12 ...

And srand(2) results in:

4 9 5 3 4 9 5 3 ...

note that they both have a period of four, but the values that are
cycled are completely different.


That applies to the second "Not necessarily." comment,
which I did not dispute.

But can this happen in a PRNG with an n-bit state and a
2**n-1 period? Am I correct in stating that in such a case there
is only ONE sequence and srand() merely positions to a new
starting point in that one sequence? For srand() to cause
completely different sequences don't you need either more
bits in the state or else a different algorithm for each value
passed to srand()?

Feb 28 '06 #54
Keith Thompson <ks***@mib.org> writes:
Micah Cowan <mi***@cowan.name> writes:
[...]
It means that at some point, it will start over again from the
beginning.

Consider a really dumb PNRG that only ever has a cycle of four
different outputs. Perhaps srand(1) will result in the sequence:

1 6 3 12 1 6 3 12 ...

And srand(2) results in:

4 9 5 3 4 9 5 3 ...

note that they both have a period of four, but the values that are
cycled are completely different.
The random number generator has at least 8 distinct states (3 bits),
which means it *could* have a cycle of 8 outputs, making full use of
its internal state. For example, srand(1) might result in:

1 6 3 12 4 9 5 3 1 6 3 12 4 9 5 3

and srand(2) might result in:

4 9 5 3 1 6 3 12 4 9 5 3 1 6 3 12


Yes, but this has nothing to do with the point I was making, which was
to answer the question that was asked:
Walter Roberson wrote:
In article <11*********************@t39g2000cwt.googlegroups. com>,
me********@aol.com <me********@aol.com> wrote:
When it's stated that
"...the Mersenne Twister as the core generator.
It produces 53-bit precision floats and has a period of 2**19937-1."

Doesn't it mean that there are 2**19937-1 states and if one were
to actually call it 2**19937 times, then one would be right back
where one started regardless of what number srand() was called with?


Not necessarily.


Then what does "period" mean?

Feb 28 '06 #55
"me********@aol.com" <me********@aol.com> writes:
Micah Cowan wrote:
"me********@aol.com" <me********@aol.com> writes:
Walter Roberson wrote:
> In article <11*********************@t39g2000cwt.googlegroups. com>,
> me********@aol.com <me********@aol.com> wrote:
>
> >When it's stated that
> > "...the Mersenne Twister as the core generator.
> > It produces 53-bit precision floats and has a period of 2**19937-1."
>
> >Doesn't it mean that there are 2**19937-1 states and if one were
> >to actually call it 2**19937 times, then one would be right back
> >where one started regardless of what number srand() was called with?
>
> Not necessarily.

Then what does "period" mean?
It means that at some point, it will start over again from the
beginning.


Isn't that what I said? The issue HERE is how can a periodic
function NOT return eventually to where it started?


Oh, yeah, apparently. Guess I misread again.
But can this happen in a PRNG with an n-bit state and a
2**n-1 period?
Actually, I think you mean 2**n period. Use a very small n to consider it.
Am I correct in stating that in such a case there
is only ONE sequence and srand() merely positions to a new
starting point in that one sequence?
That seems right to me.
For srand() to cause
completely different sequences don't you need either more
bits in the state or else a different algorithm for each value
passed to srand()?


The second case is essentially the same as the first, I think; but
either way I believe that's a yes.
Feb 28 '06 #56
In article <11*********************@t39g2000cwt.googlegroups. com>,
me********@aol.com <me********@aol.com> wrote:
When it's stated that
"...the Mersenne Twister as the core generator.
It produces 53-bit precision floats and has a period of 2**19937-1." Doesn't it mean that there are 2**19937-1 states and if one were
to actually call it 2**19937 times, then one would be right back
where one started regardless of what number srand() was called with?


Period is the length of the cycle, but there can be an indefinite
number of states before it enters the cycle.

Trivial example:

static unsigned int just_seeded = 1;
static unsigned int seed = 1;

void srand(unsigned int newseed) {
just_seeded = 1 + (newseed - 1) % 31415;
seed = newseed;
}

int rand(void) {
int new_rand_num
if (just_seeded == 0) {
new_rand_num = /* regular PNRG goes here */
} else {
just_seeded--;
new_rand_num = 42;
}
return new_rand_num;
}

That is, emit 42 between 1 and 31415 times (dependant upon the seed)
before entering into the cycle. When you finally encounter 42
"naturally" you will not be back where you started, and if the period
is 2**19937-1 then after that many calls, you will not be back where
you started either. Indeed, no matter how many calls you make
to rand() without srand(), you never get back where you started
with this particular rand().
--
"law -- it's a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)
Feb 28 '06 #57
In article <11**********************@v46g2000cwv.googlegroups .com>,
me********@aol.com <me********@aol.com> wrote:
For srand() to cause
completely different sequences don't you need either more
bits in the state
More bits than what? The state is not necessarily restricted
to the number of bits in an unsigned int (i.e., the argument to srand()),
and different arguments of srand() do not necessarily affect the same
state bits in the same way.
or else a different algorithm for each value
passed to srand()?


static unsigned long m_list[] = { /* list of possible multipliers */ };
static unsigned long c_list[] = { /* list of possible constants */ };
static unsigned long current_m = /* second element of m_list */;
static unsigned long current_c = /* second element of c_list */;
static unsigned long seed = 1;

void srand( unsigned int newseed ) {
seed = newseed;
current_m = m_list[seed % (sizeof m_list / sizeof m_list[0])];
current_c = c_list[seed % (sizeof c_list / sizeof c_list[0])];
}

int rand(void) {
/* insert a LCG with coefficients current_m and current_c */
}

If the sizes of m_list and c_list were mutually prime and the
product of the sizes was greater than UINT_MAX then you would
produce a different PNRG for every possible seed, and yet it
would be exactly the same algorithm for each of them.
--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Feb 28 '06 #58
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <11**********************@v46g2000cwv.googlegroups .com>,
me********@aol.com <me********@aol.com> wrote:
For srand() to cause
completely different sequences don't you need either more
bits in the state


More bits than what? The state is not necessarily restricted
to the number of bits in an unsigned int (i.e., the argument to srand()),
and different arguments of srand() do not necessarily affect the same
state bits in the same way.


You snipped the answer to your question. More bits than n, to produce
more than one sequence, if one of the sequences has a period of 2**n.

-Micah
Mar 1 '06 #59

Walter Roberson wrote:
In article <11*********************@t39g2000cwt.googlegroups. com>,
me********@aol.com <me********@aol.com> wrote:
When it's stated that
"...the Mersenne Twister as the core generator.
It produces 53-bit precision floats and has a period of 2**19937-1."
Doesn't it mean that there are 2**19937-1 states and if one were
to actually call it 2**19937 times, then one would be right back
where one started regardless of what number srand() was called with?


Period is the length of the cycle, but there can be an indefinite
number of states before it enters the cycle.

Trivial example:

static unsigned int just_seeded = 1;
static unsigned int seed = 1;

void srand(unsigned int newseed) {
just_seeded = 1 + (newseed - 1) % 31415;
seed = newseed;
}

int rand(void) {
int new_rand_num
if (just_seeded == 0) {
new_rand_num = /* regular PNRG goes here */
} else {
just_seeded--;
new_rand_num = 42;
}
return new_rand_num;
}

That is, emit 42 between 1 and 31415 times (dependant upon the seed)
before entering into the cycle. When you finally encounter 42
"naturally" you will not be back where you started, and if the period
is 2**19937-1 then after that many calls, you will not be back where
you started either. Indeed, no matter how many calls you make
to rand() without srand(), you never get back where you started
with this particular rand().


Ok, I accept the "not necessarily" comments.

But if all you have to go by is the standard, the issue remains:

should you call srand() more than once to "improve" the randomness?

I've been trying to justify answering no, but if those justifications
don't necessarily hold, does the answer change to yes, or does it
remain no?

--
"law -- it's a commodity"
-- Andrew Ryan (The Globe and Mail, 2005/11/26)


Mar 1 '06 #60
In article <du**********@canopus.cc.umanitoba.ca> ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <11*********************@t39g2000cwt.googlegroups. com>,
me********@aol.com <me********@aol.com> wrote:
When it's stated that
"...the Mersenne Twister as the core generator.
It produces 53-bit precision floats and has a period of 2**19937-1."
Doesn't it mean that there are 2**19937-1 states and if one were
to actually call it 2**19937 times, then one would be right back
where one started regardless of what number srand() was called with?


Not necessarily.


Indeed, it does *not* mean that there are 2**19937-1 states, there may
be more. But it *does* mean that after calling it 2**19937-1 times
you are back at the original state. It is possible that the collection
of different states is a multiple of 2**19937-1, containing different
loops, each 2**19937-1 long.

Consider the following (extremely simple) random number generator:
s = (2 * s) % 17;
It has 16 states, but a period of 8. One cycle is:
1 -> 2 -> 4 -> 8 -> 16 -> 15 -> 13 -> 9 -> 1
the other is:
3 -> 6 -> 12 -> 7 -> 14 -> 11 -> 5 -> 10 -> 3
I do not know whether that is possible with a period of 2**19937-1, but
I can not exclude it, and I think it is extremely likely that it is
possible.

.... If we put these together, we would see that srand(1) and srand(2)
would have the same cycles -only- if it happened the the linear
congruential generator applied to 0x1330E16 happened to result
in 0x2330E16 at some point.
Indeed, but a question is also, what is the period of the generator?
Further analysis would be needed to
see whether that ever happened -- the default multiplier and
constant for drand48() and kin are both even, so it is not
the usual case that "every possible n-bit value will be generated,
eventually".


Indeed, the least significant bit will always be 0. What I am wondering
however, what does
"the low-order 16 bits of Xi are set to the arbitrary value 330E16."
mean? By any reasonable interpretation of "330E16" I come to a value
where the low order 16 bits are 0.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Mar 1 '06 #61
In article <ln************@nuthaus.mib.org> Keith Thompson <ks***@mib.org> writes:
....
But, as you said, it's a really dumb RNG. Generally speaking, using
only a subset of the available state for a given sequence is allowed
by the standard, but *probably* not a good idea (unless the state is
large enough that a subset of it gives you a very long repeating cycle
anyway).


Given a number of possible states it can be the case that a RNG that
splits it in two (or more) cycles has better quality than a RNG that
is forced to use all states in cycle. That is one of the problems
of the standard rand. It is full cycle, but the low-order bits
display a lot of non-randomness.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Mar 1 '06 #62
In article <Iv********@cwi.nl>, Dik T. Winter <Di********@cwi.nl> wrote:
What I am wondering
however, what does
"the low-order 16 bits of Xi are set to the arbitrary value 330E16."
mean? By any reasonable interpretation of "330E16" I come to a value
where the low order 16 bits are 0.


Checking the opengroup man page for drand48(), I see that it has

330E
16

which in C notation would be 0x330E .

It would appear that the other constants were similarily mangled in
the man page I was consulting: the standard multiplier is
0x5DEECE66D and the standard additive constant is 0xB or 013 (octal).
The opengroup man page uses subscripts for the bases but those
got raised on the page I was consulting so that it appears to say
B16 = 138 ... I didn't notice the complete discrepancy in magnitudes
there.

With the corrected constants, drand48() -does- alternate even
and odd, so -eventually- the state value stored for
srand(1) (0x1 << 16 | 0x330E) would get transformed into the state
value stored for srand(2) (0x2 << 16 | 0x330E) so drand48()
does turn out to be an example of a generator in which srand48(1)
and srand48(2) will produce the same cycle, just starting at
at different point in the cycle.
--
There are some ideas so wrong that only a very intelligent person
could believe in them. -- George Orwell
Mar 1 '06 #63
me********@aol.com wrote:
Walter Roberson wrote:
me********@aol.com <me********@aol.com> wrote:
When it's stated that
"...the Mersenne Twister as the core generator.
It produces 53-bit precision floats and has a period of 2**19937-1."

Doesn't it mean that there are 2**19937-1 states and if one were
to actually call it 2**19937 times, then one would be right back
where one started regardless of what number srand() was called with?


Not necessarily.


Then what does "period" mean?


I think it means that each seed indexes a sequence with a period of
2**19937-1. But its not necessarily the same sequence.

Looking at the source of the Mersenne Twister, it appears to have at
most 2**19968 possible internal states. That basically means that
there are at most 2**31 disjoint sequences, if indeed MT has this
property. More likely, there is just one large cycle possible, and you
can pick one possible position with your initialization seed array. We
know that there is at least one degenerate state: the all 0s state, for
example, has a period of 1, so there are at most 2**31-1 cycles of
length 2**19937-1.
It would be possible to the initial seed to affect parameters
in the PRNG, such that srand(1) and srand(2) each had the same
period, but that the cyles for the two were not the same.


Ok, but we can't infer that from the standard, can we?


The C standard does not address the quality of random numbers.
(Resisting the urge to make the obvious generalization of this
statement ...)

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

Mar 1 '06 #64
On Tue, 28 Feb 2006 17:28:10 -0800, me********@aol.com wrote:
But if all you have to go by is the standard, the issue remains:

should you call srand() more than once to "improve" the randomness?

I've been trying to justify answering no, but if those justifications
don't necessarily hold, does the answer change to yes, or does it remain
no?


The short answer is no, don't call srand more than once per program
execution. Even if you use so many calls of rand that the sequence wraps
round, the wrapped sequence will be as good as anything you can get by
re-seeding (and probably less predictable to observers as well).

Given that this is Usenet, let me qualify this. The very fact that
srand/rand is being used means that either: (a) you know that your
implementation is a good one (glibc's rand looks good to me) and calling
srand will just "get in its way" or (b) you don't have sophisticated needs
anyway so why give your program's readers something else to worry about?

The long answer requires two more pieces of information: what do you mean
by "randomness" and with what actual parameters will you call srand?

Assuming you have normal requirements for (pseudo-) randomness, an
exacting enough application to be worrying about this, and a good enough
source of entropy (sort of "real-world" randomness) you will probably have
replaced srand/rand with something more sophisticated (or examined your
implementation to see that it is OK for your needs) and you will use some
of your entropy to seed the generator at logical points in your program.
These points will not be every few calls to rand "just to help it out" but
will be when it makes sense to use your usually precious entropy for a
seed -- shuffling a multi-deck card shoe, generating a cryptographic key,
etc.

There is a special case that needs consideration -- that of programs that
do not terminate but call rand a lot since the "call srand once per
execution" advice may not be suitable for these. How often one should
call srand for such a program will vary from case to case.

--
Ben.
Mar 1 '06 #65

<me********@aol.com> wrote in message
news:11**********************@e56g2000cwe.googlegr oups.com...

Nelu wrote:
me********@aol.com wrote:
Rod Pemberton wrote:
>
> KEITH: NO! Completely incorrect! This is the fifth time and last time. > Since I'm tied of trying to get through to you, I'll just repeat what I > posted to Sinaur. If you don't comprehend, you can deal with your
> inabilities in private.
>
> "As I've stated previously, the randomness is in the non-perfect algorithm > in rand(). But, the set of numbers generated by rand() is affected by > srand().

No, it's not. There is only ONE sequence.

Not entirely sure about this. It depends on how the RNG generates the
numbers and I'm not sure that the standard says the algorithm has to be
a specific one. If it generates numbers based on previously generated
numbers you may be wrong.


If I'm wrong, then calling srand() with a constant would not
give you the same sequence, would it?


The function is continuous. Think of sin() and cos(). They have the exact
same appearance, but the set of numbers generated is different. If, for
example, rand() started by generating sin() instead of some other algorithm,
calling srand() will give the function a different starting point and a
different set of generated numbers, which could be cos().

Rod Pemberton
Mar 2 '06 #66

"A. Sinan Unur" <1u**@llenroc.ude.invalid> wrote in message
news:Xn***************************@127.0.0.1...
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> wrote in
news:du***********@news3.infoave.net:
"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> writes:
> "A. Sinan Unur" <1u**@llenroc.ude.invalid> wrote in message
> news:Xn****************************@127.0.0.1...
>> "Rod Pemberton" <do*********@sorry.bitbucket.cmm> wrote in
>> news:dt***********@news3.infoave.net:
>> > "Keith Thompson" <ks***@mib.org> wrote in message
>> > news:ln************@nuthaus.mib.org...
>> ...
>> >> Calling srand() more than once
>> >> makes sense *only* if you want to repeat the same sequence.
>> >
>> > False.
>> >
>> > You apparently meant to say this: "'Calling srand() more than
>> > once' _with_the_same_value_ 'makes sense *only* if you want to
>> > repeat the same sequence.'"
>>
>> You are misreading Keith's post. Calling srand multiple times with
>> different seeds during the life time of the program *decreases*
>> the randomness of the sequence generated.
>
> False.
>
> What you are claiming is that the randomness of the sequence
> increases as the rand() function is used.

No, nobody made that claim.

[snip]

> By calling srand() we increased the probability of
> some numbers which had low probability and reduced the probability
> of other numbers which had low probability.
This is nonsense.
So you're asserting that repeatedly calling srand() improves the
randomness of the numbers returned by rand()? In particular, you're
claming that that something like this:

<snip>
is likely to yield better (more random) results than if the second
call to srand() were removed (perhaps with a different number of
calls)?


KEITH: NO! Completely incorrect! This is the fifth time and last
time. Since I'm tied of trying to get through to you, I'll just repeat
what I posted to Sinaur.


The correct spelling of my name is 'Sinan'.
If you don't comprehend, you can deal with your inabilities in
private.


It is impossible for me to comprehend what you are saying because it
makes no sense. There are a number of standard texts on pseudo RNGs. I
suggest you look them up, and try to find one that recommends constant
reseeding as a way of improving 'randomness'.
"As I've stated previously, the randomness is in the non-perfect
algorithm in rand().


There is no 'the' algorithm in rand(). There are many different
algorithms, and even the simplest ones may differ in the choice of
parameters.
But, the set of numbers generated by rand() is
affected by srand(). srand() doesn't affect the randomness of values
that rand() generates, it only changes the set of generated numbers.
Since the algorithm isn't a perfect-random number generator but a
pseudo-random number generator, the probabilities of certain numbers
occurring is higher than others. These probabilities can be shifted
by calls to srand(). "


But not, in general, in a way that makes the resulting sequence exhibit
desirable properties such as lack of autocorrelation or other patterns.
Consider the simple example:

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

void re_seed(int seed) {
#ifdef HOSE_ME
srand(seed);
#endif
}

int main(int argc, char *argv[]) {
int i, count;
if ( argc == 1 ) {
count = 1000;
} else {
count = atoi(argv[1]);
}
srand(time(NULL));

for ( i = 0; i < count; ++i ) {
int ri = rand();
re_seed(ri);
printf("%d\n", ri);
}

return 0;
}

/*EOF*/

Compile this program, examine generated sequences. I generated 10
sequences of 100 numbers with HOSE_ME defined, and 10 without.

Then I tested each sequence for autocorrelation. Every sequence with
HOSE_ME defined showed statistically significant autocorrelation at
alpha = 5% where none of the sequences without HOSE_ME defined did.

This is, of course, not a proof, but an example of what we are trying to
get across to you.


I understood what you and Keith were trying to demonstrate. It seems
neither one of you understand that there is no randomness created by calling
srand(). If you had read and understood my posts, you'd know that you are
calling srand() far to frequently (in fact, you'd also need to insert a
check to wait until srand() changes). The error in your code is that you
never allow rand() to generate any psuedo-random numbers before calling
srand().

Repeating what I just posted to Nelu:
"Think of sin() and cos(). They have the exact same appearance, but the set
of numbers generated is different. If, for example, rand() started by
generating sin(), instead of some other algorithm, calling srand() will give
the function a different starting point and a different set of generated
numbers, which could be cos()."

Rod Pemberton

PS. Sorry about the error with your name, I looked at it to quickly and
dropped some letters...
Mar 2 '06 #67
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> writes:
<me********@aol.com> wrote in message
news:11**********************@e56g2000cwe.googlegr oups.com... [...]
If I'm wrong, then calling srand() with a constant would not
give you the same sequence, would it?


The function is continuous.


I think I understand what you're saying, but the function (whatever
function you're thinking of) is *not* continuous in the usual
mathematical sense.
Think of sin() and cos(). They have the exact
same appearance, but the set of numbers generated is different. If, for
example, rand() started by generating sin() instead of some other algorithm,
calling srand() will give the function a different starting point and a
different set of generated numbers, which could be cos().


So you're assuming that rand() generates a (presumably repeating)
sequence of numbers, and srand() causes it to start at a position
within that sequence. As we've been discussing, that's possible but
not required; it's also possible that rand() could generate any of a
number of disjoint sequences, and srand() could cause it to jump from
one sequence to another.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 2 '06 #68
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> writes:
[...]
I understood what you and Keith were trying to demonstrate. It seems
neither one of you understand that there is no randomness created by calling
srand(). If you had read and understood my posts, you'd know that you are
calling srand() far to frequently (in fact, you'd also need to insert a
check to wait until srand() changes). The error in your code is that you
never allow rand() to generate any psuedo-random numbers before calling
srand().


Remarkable.

I understand perfectly well that calling srand() does not create any
randomness. As for calling srand() too frequently, we have done so
*only* in sample programs intended to demonstrate that doing so is a
bad idea.

I have consistently advocated calling srand() once and only once in a
program, before any calls to rand().

Several days ago in this thread, I wrote:
] Calling srand() more than once makes sense *only* if you want to
] repeat the same sequence.

You disagreed (and tried to tell me that I really meant to say
something else). Have you changed your mind?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 2 '06 #69

Rod Pemberton wrote:
<me********@aol.com> wrote in message
news:11**********************@e56g2000cwe.googlegr oups.com...

Nelu wrote:
me********@aol.com wrote:
> Rod Pemberton wrote:
> >
> > KEITH: NO! Completely incorrect! This is the fifth time and last time. > > Since I'm tied of trying to get through to you, I'll just repeat what I > > posted to Sinaur. If you don't comprehend, you can deal with your
> > inabilities in private.
> >
> > "As I've stated previously, the randomness is in the non-perfect algorithm > > in rand(). But, the set of numbers generated by rand() is affected by > > srand().
>
> No, it's not. There is only ONE sequence.
Not entirely sure about this. It depends on how the RNG generates the
numbers and I'm not sure that the standard says the algorithm has to be
a specific one. If it generates numbers based on previously generated
numbers you may be wrong.


If I'm wrong, then calling srand() with a constant would not
give you the same sequence, would it?


The function is continuous. Think of sin() and cos(). They have the exact
same appearance, but the set of numbers generated is different. If, for
example, rand() started by generating sin() instead of some other algorithm,
calling srand() will give the function a different starting point and a
different set of generated numbers, which could be cos().

Rod Pemberton


Right, I've been saying that to mensanator I think. Reseeding does not
necesarily change your position in the sequence of generated data. I've
been also saying that reseeding often makes sense only if you use a RNG
to generate de reseeding sequence (wrapping a problem into a
problematic solution) or making sure that the sequence can't be found
out (keep it secret or use a better RNG to generate the seeds which is,
again, pointless, as you could use the other RNG to generate your
numbers) and that seeding once is enough.

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)

Mar 2 '06 #70
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> wrote in
news:du**********@news3.infoave.net:
The function is continuous. Think of sin() and cos(). They have the
exact same appearance, but the set of numbers generated is different.
If, for example, rand() started by generating sin() instead of some
other algorithm, calling srand() will give the function a different
starting point and a different set of generated numbers, which could
be cos().


And, the sequence generated by knowing the sequence generated by one, you
can generate the exact sequence generated by the other. If you mix the
sequences, you create a martingale:

http://en.wikipedia.org/wiki/Martingale

I don't see how that is a desirable property of a sequence generated by a
pseudo RNG.

Sinan

--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)

comp.lang.perl.misc guidelines on the WWW:
http://mail.augustmail.com/~tadmc/cl...uidelines.html

Mar 2 '06 #71
Keith Thompson <ks***@mib.org> writes:
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> writes:
[...]
I understood what you and Keith were trying to demonstrate. It seems
neither one of you understand that there is no randomness created by calling
srand(). If you had read and understood my posts, you'd know that you are
calling srand() far to frequently (in fact, you'd also need to insert a
check to wait until srand() changes). The error in your code is that you
never allow rand() to generate any psuedo-random numbers before calling
srand().
Remarkable.

I understand perfectly well that calling srand() does not create any
randomness. As for calling srand() too frequently, we have done so
*only* in sample programs intended to demonstrate that doing so is a
bad idea.


Yes, he seems to have completely misunderstood you. However, he never
recommended calling srand() before every rand(), as you've done in
your example code.
I have consistently advocated calling srand() once and only once in a
program, before any calls to rand().

Several days ago in this thread, I wrote:
] Calling srand() more than once makes sense *only* if you want to
] repeat the same sequence.

You disagreed (and tried to tell me that I really meant to say
something else). Have you changed your mind?


I doubt it. But his answer was at least somewhat valid, as he
advocated calling srand() every once in a while (every shuffle, or
every 52 calls to rand()), based on a fairly random interval of time
between srand()s (namely, the time it takes one to go through a deck
of cards in a card game).

-Micah
Mar 2 '06 #72
Micah Cowan <mi***@cowan.name> writes:
Keith Thompson <ks***@mib.org> writes:
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> writes:
[...]
> I understood what you and Keith were trying to demonstrate. It
> seems neither one of you understand that there is no randomness
> created by calling srand(). If you had read and understood my
> posts, you'd know that you are calling srand() far to frequently
> (in fact, you'd also need to insert a check to wait until srand()
> changes). The error in your code is that you never allow rand()
> to generate any psuedo-random numbers before calling srand().


Remarkable.

I understand perfectly well that calling srand() does not create any
randomness. As for calling srand() too frequently, we have done so
*only* in sample programs intended to demonstrate that doing so is a
bad idea.


Yes, he seems to have completely misunderstood you. However, he never
recommended calling srand() before every rand(), as you've done in
your example code.


Have you confused me with someone else? I just re-examined everything
I've posted to this thread. I have never recommended calling srand()
before every rand(). (I didn't check all the articles, but I don't
think anyone else did either.) I posted a sample code snippet in
which srand() is called before every 3 calls to rand(), along with a
clear statement that it was only an example, and the number of calls
could be different. That was *not* a recommendation; I was asking Rod
Pemberton whether *he* thought that would be a good idea.
I have consistently advocated calling srand() once and only once in a
program, before any calls to rand().

Several days ago in this thread, I wrote:
] Calling srand() more than once makes sense *only* if you want to
] repeat the same sequence.

You disagreed (and tried to tell me that I really meant to say
something else). Have you changed your mind?


I doubt it. But his answer was at least somewhat valid, as he
advocated calling srand() every once in a while (every shuffle, or
every 52 calls to rand()), based on a fairly random interval of time
between srand()s (namely, the time it takes one to go through a deck
of cards in a card game).


Unless you specifically want to repeat the same sequence of
pseudo-random numbers, you should call rand() exactly once, before any
calls to rand(). If that doesn't give you good results, the solution
is to use a different pseudo-random number generator, not to call
srand() more than once. rand() is specifically designed to be
repeatable, and therefore predictable given sufficient knowledge; if
that's a problem, don't use it.

It's possible that careful re-seeding might give you better results
with some implementations of rand(), but given the availability of
free high-quality PRNGs, there's no point in bothering with that kind
of thing; any techniques you come up with won't apply to other
implementations anyway.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 2 '06 #73
Keith Thompson <ks***@mib.org> writes:
[...]
Unless you specifically want to repeat the same sequence of
pseudo-random numbers, you should call rand() exactly once, before any
calls to rand(). If that doesn't give you good results, the solution
is to use a different pseudo-random number generator, not to call
srand() more than once. rand() is specifically designed to be
repeatable, and therefore predictable given sufficient knowledge; if
that's a problem, don't use it.

[...]

Sorry, I meant:

Unless you specifically want to repeat the same sequence of
pseudo-random numbers, you should call *srand()* exactly once, before
any calls to rand().

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 2 '06 #74
[thread hijack]

Does the standard guarantee the output of this program is the same on
all implementations (that have stdlib.h)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
printf("%d\n", rand());
srand(42);
printf("%d\n", rand());
return 0;
}
On my system (I don't have a compiler for my other OS here at home)
it outputs these numbers:

1804289383
71876166
--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Mar 2 '06 #75
Keith Thompson <ks***@mib.org> writes:
Micah Cowan <mi***@cowan.name> writes:
Keith Thompson <ks***@mib.org> writes:
"Rod Pemberton" <do*********@sorry.bitbucket.cmm> writes:
[...]
> I understood what you and Keith were trying to demonstrate. It
> seems neither one of you understand that there is no randomness
> created by calling srand(). If you had read and understood my
> posts, you'd know that you are calling srand() far to frequently
> (in fact, you'd also need to insert a check to wait until srand()
> changes). The error in your code is that you never allow rand()
> to generate any psuedo-random numbers before calling srand().

Remarkable.

I understand perfectly well that calling srand() does not create any
randomness. As for calling srand() too frequently, we have done so
*only* in sample programs intended to demonstrate that doing so is a
bad idea.
Yes, he seems to have completely misunderstood you. However, he never
recommended calling srand() before every rand(), as you've done in
your example code.


Have you confused me with someone else? I just re-examined everything
I've posted to this thread. I have never recommended calling srand()
before every rand(). (I didn't check all the articles, but I don't
think anyone else did either.) I posted a sample code snippet in
which srand() is called before every 3 calls to rand(), along with a
clear statement that it was only an example, and the number of calls
could be different. That was *not* a recommendation; I was asking Rod
Pemberton whether *he* thought that would be a good idea.


I never said you recommended any such thing. I said that your code did
so. This is apparently wrong, as it is actually Sinan's code I'm
referring to, after checking up on it. So yes, to some degree, I'm
getting you confused.
I have consistently advocated calling srand() once and only once in a
program, before any calls to rand().

Several days ago in this thread, I wrote:
] Calling srand() more than once makes sense *only* if you want to
] repeat the same sequence.

You disagreed (and tried to tell me that I really meant to say
something else). Have you changed your mind?


I doubt it. But his answer was at least somewhat valid, as he
advocated calling srand() every once in a while (every shuffle, or
every 52 calls to rand()), based on a fairly random interval of time
between srand()s (namely, the time it takes one to go through a deck
of cards in a card game).


Unless you specifically want to repeat the same sequence of
pseudo-random numbers, you should call rand() exactly once, before any
calls to rand().


(You meant srand() instead of the first rand())

Calling srand() more than once will not repeat the same sequence of
pseudo-random numbers, unless you stupidly provide it with the same
input as the last time. I'm fairly certain Rod intended that you call
it each time with a time-based value.
If that doesn't give you good results, the solution
is to use a different pseudo-random number generator, not to call
srand() more than once.


I don't see how that follows.
Mar 2 '06 #76
Pedro Graca <he****@dodgeit.com> writes:
[thread hijack]

Does the standard guarantee the output of this program is the same on
all implementations (that have stdlib.h)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
printf("%d\n", rand());
srand(42);
printf("%d\n", rand());
return 0;
}
On my system (I don't have a compiler for my other OS here at home)
it outputs these numbers:

1804289383
71876166


No. It is guaranteed to return the same output each time you run it on
the same implementation... but individual implementations are quite
free in their choice of what to produce.

-Micah
Mar 2 '06 #77
Pedro Graca wrote:
[thread hijack]

Does the standard guarantee the output of this program is the same on
all implementations (that have stdlib.h)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
printf("%d\n", rand());
srand(42);
printf("%d\n", rand());
return 0;
}
On my system (I don't have a compiler for my other OS here at home)
it outputs these numbers:

1804289383
71876166


Same for me (SUSE Linux 10.0).

However, the Standard does not prescribe the implementation of rand()
and srand() (7.20.2.2p5). It does, however, give a portable example
implementation, but it's by no means required to be used.

--
BR, Vladimir

Don't quit now, we might just as well
lock the door and throw away the key.

Mar 2 '06 #78
On Thu, 02 Mar 2006 21:23:29 GMT, Micah Cowan <mi***@cowan.name>
wrote:
Keith Thompson <ks***@mib.org> writes:
Micah Cowan <mi***@cowan.name> writes:
> Keith Thompson <ks***@mib.org> writes:

Unless you specifically want to repeat the same sequence of
pseudo-random numbers, you should call rand() exactly once, before any
calls to rand().


(You meant srand() instead of the first rand())

Calling srand() more than once will not repeat the same sequence of
pseudo-random numbers, unless you stupidly provide it with the same
input as the last time. I'm fairly certain Rod intended that you call
it each time with a time-based value.

s/stupidly/intentionally. Then consider the phrase "Unless you
specifically want to repeat the same sequence" above.

--
Al Balmer
Sun City, AZ
Mar 2 '06 #79
Al Balmer <al******@att.net> writes:
On Thu, 02 Mar 2006 21:23:29 GMT, Micah Cowan <mi***@cowan.name>
wrote:
Keith Thompson <ks***@mib.org> writes:
Micah Cowan <mi***@cowan.name> writes:
> Keith Thompson <ks***@mib.org> writes:
Unless you specifically want to repeat the same sequence of
pseudo-random numbers, you should call rand() exactly once, before any
calls to rand().
(You meant srand() instead of the first rand())

Calling srand() more than once will not repeat the same sequence of
pseudo-random numbers, unless you stupidly provide it with the same
input as the last time. I'm fairly certain Rod intended that you call
it each time with a time-based value.

s/stupidly/intentionally.


No; srand() will repeat the same sequence of pseudo-random numbers,
whether you did it intentionally or stupidly, so I think my original
phrasing is fine.
Then consider the phrase "Unless you
specifically want to repeat the same sequence" above.


Which clearly no one on this thread /does/ want.

-Micah
Mar 2 '06 #80
In article <sl*******************@ID-203069.user.individual.net>,
Pedro Graca <he****@hotpop.com> wrote:
[thread hijack] Does the standard guarantee the output of this program is the same on
all implementations (that have stdlib.h) #include <stdio.h>
#include <stdlib.h> int main(void) {
printf("%d\n", rand());
srand(42);
printf("%d\n", rand());
return 0;
}


No.

Gee, I guess that means that "C isn't portable!" ;-)
--
Is there any thing whereof it may be said, See, this is new? It hath
been already of old time, which was before us. -- Ecclesiastes
Mar 2 '06 #81
On Thu, 02 Mar 2006 21:46:46 GMT, Micah Cowan <mi***@cowan.name>
wrote:
Al Balmer <al******@att.net> writes:
On Thu, 02 Mar 2006 21:23:29 GMT, Micah Cowan <mi***@cowan.name>
wrote:
>Keith Thompson <ks***@mib.org> writes:
>
>> Micah Cowan <mi***@cowan.name> writes:
>> > Keith Thompson <ks***@mib.org> writes:
>> Unless you specifically want to repeat the same sequence of
>> pseudo-random numbers, you should call rand() exactly once, before any
>> calls to rand().
>
>(You meant srand() instead of the first rand())
>
>Calling srand() more than once will not repeat the same sequence of
>pseudo-random numbers, unless you stupidly provide it with the same
>input as the last time. I'm fairly certain Rod intended that you call
>it each time with a time-based value.
>

s/stupidly/intentionally.


No; srand() will repeat the same sequence of pseudo-random numbers,
whether you did it intentionally or stupidly, so I think my original
phrasing is fine.

Perhaps you should not have made it appear to be a comment on what
Keith wrote, then. I thought you intended something more than just a
random injection of a truism.
Then consider the phrase "Unless you
specifically want to repeat the same sequence" above.


Which clearly no one on this thread /does/ want.

-Micah


--
Al Balmer
Sun City, AZ
Mar 2 '06 #82
Micah Cowan wrote:

Pedro Graca <he****@dodgeit.com> writes:
[thread hijack]

Does the standard guarantee the output of this program is the same on
all implementations (that have stdlib.h)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
printf("%d\n", rand());
srand(42);
printf("%d\n", rand());
return 0;
}
[...]
No. It is guaranteed to return the same output each time you run it on
the same implementation... but individual implementations are quite
free in their choice of what to produce.


Does the standard require that rand() return the same sequence each time
a program is run, if srand() is never called?

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Mar 2 '06 #83
In article <44***************@spamcop.net>,
Kenneth Brody <ke******@spamcop.net> wrote:
Does the standard require that rand() return the same sequence each time
a program is run, if srand() is never called?


Yes, neglecting to call srand() is equivilent to using srand(1)
according to the C89 description of srand().
--
I was very young in those days, but I was also rather dim.
-- Christopher Priest
Mar 2 '06 #84
Al Balmer <al******@att.net> writes:
On Thu, 02 Mar 2006 21:46:46 GMT, Micah Cowan <mi***@cowan.name>
wrote:
Al Balmer <al******@att.net> writes:
On Thu, 02 Mar 2006 21:23:29 GMT, Micah Cowan <mi***@cowan.name>
wrote:

>Keith Thompson <ks***@mib.org> writes:
>
>> Micah Cowan <mi***@cowan.name> writes:
>> > Keith Thompson <ks***@mib.org> writes:
>> Unless you specifically want to repeat the same sequence of
>> pseudo-random numbers, you should call rand() exactly once, before any
>> calls to rand().
>
>(You meant srand() instead of the first rand())
>
>Calling srand() more than once will not repeat the same sequence of
>pseudo-random numbers, unless you stupidly provide it with the same
>input as the last time. I'm fairly certain Rod intended that you call
>it each time with a time-based value.
>
s/stupidly/intentionally.


No; srand() will repeat the same sequence of pseudo-random numbers,
whether you did it intentionally or stupidly, so I think my original
phrasing is fine.

Perhaps you should not have made it appear to be a comment on what
Keith wrote, then. I thought you intended something more than just a
random injection of a truism.


It was a comment on what he wrote. My point is that calling srand()
more than once /can/ have purposes beyond repeating the same sequence
of pseudo-random numbers, contrary to what Keith implied. Is no one on
this thread actually reading before they post? I've been seeing
nothing but constant misreading from every single contributor on this
thread (and yes, that includes me for at least one mistaken
attribution). I only jumped in to point out that people were making
blatantly false assumptions regarding other people's points; but as
this has continued unabated, I don't see the point in following this
thread any more.

I don't agree, generally, with what Rod's suggesting, but I was trying
to at least clarify that his point was rather different from what was
being claimed by others (Sinan still seems confused, at least), and
could actually be good advice in some very limited situations (in
applications such as he described [card games] and with /extremely/
poor PRNGs, or a very long-lived card player ;-) ).

If y'all aren't prepared to carefully read what you're responding to,
you probably shouldn't be responding in the first place. I'll also
note that the level of civility on this thread has been quite poor on
both sides (but not by all contributors).
Mar 2 '06 #85
Micah Cowan <mi***@cowan.name> writes:
Keith Thompson <ks***@mib.org> writes:
Micah Cowan <mi***@cowan.name> writes: [...]
> Yes, he seems to have completely misunderstood you. However, he never
> recommended calling srand() before every rand(), as you've done in
> your example code.
Have you confused me with someone else? I just re-examined everything
I've posted to this thread. I have never recommended calling srand()
before every rand(). (I didn't check all the articles, but I don't
think anyone else did either.) I posted a sample code snippet in
which srand() is called before every 3 calls to rand(), along with a
clear statement that it was only an example, and the number of calls
could be different. That was *not* a recommendation; I was asking Rod
Pemberton whether *he* thought that would be a good idea.


I never said you recommended any such thing. I said that your code did
so. This is apparently wrong, as it is actually Sinan's code I'm
referring to, after checking up on it. So yes, to some degree, I'm
getting you confused.


Ok. What you wrote above could reasonably be interpreted to imply
that I recommended calling srand() before every rand(), and in fact
that's how I interpreted it. I thought the "as you've done" referred
to *recommending* calling srand() rather than to calling srand().
Thanks for the clarification.

[...]
> I doubt it. But his answer was at least somewhat valid, as he
> advocated calling srand() every once in a while (every shuffle, or
> every 52 calls to rand()), based on a fairly random interval of time
> between srand()s (namely, the time it takes one to go through a deck
> of cards in a card game).


Unless you specifically want to repeat the same sequence of
pseudo-random numbers, you should call rand() exactly once, before any
calls to rand().


(You meant srand() instead of the first rand())


Yes, acknowledged elsethread.
Calling srand() more than once will not repeat the same sequence of
pseudo-random numbers, unless you stupidly provide it with the same
input as the last time. I'm fairly certain Rod intended that you call
it each time with a time-based value.


If you *want* to repeat the same sequence, calling srand with the same
argument is exactly what you want to do. (For example, you might want
to produce two identical shuffles of a deck of cards, or otherwise
allow a user to re-play the same game of whatever.)

I'm not convinced that Rod has been consistent. I suggest we wait for
him to clarify what he meant.
If that doesn't give you good results, the solution
is to use a different pseudo-random number generator, not to call
srand() more than once.


I don't see how that follows.


It doesn't follow as a matter of rigorous deductive reasoning, but it
seems to me to be a reasonable common-sense inference. Any decent
pseudo-random number generator is going to be designed to work best
when it's allowed to generate a sequence from a starting seed without
interference. If you try to second-guess the algorithm by arbitrarily
perturbing it with additional calls to srand(), there is no reason to
think that the result is going to be any better (whatever "better"
means). If you *know* that re-seeding the algorithm will generate
better results, that implies, I think, that the algorithm is
defective, and you should just use a better one (many are freely
available). A re-seeding scheme that improves one RNG is unlikely to
improve another RNG, so any code that does something like this is
going to be gratuitously non-portable anyway. Using a different RNG
doesn't even sacrifice portability; numerous RNGs are available in
portable C code.

Rod Pemberton seems to disagree with this (though I haven't been able
to figure out what he's really trying to say). He's free to explain
his reasoning if he wants to. He's also free to drop the whole thing.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 2 '06 #86
Micah Cowan <mi***@cowan.name> writes:
Al Balmer <al******@att.net> writes:
On Thu, 02 Mar 2006 21:23:29 GMT, Micah Cowan <mi***@cowan.name>
wrote: [...]
>Calling srand() more than once will not repeat the same sequence of
>pseudo-random numbers, unless you stupidly provide it with the same
>input as the last time. I'm fairly certain Rod intended that you call
>it each time with a time-based value.
>

s/stupidly/intentionally.


No; srand() will repeat the same sequence of pseudo-random numbers,
whether you did it intentionally or stupidly, so I think my original
phrasing is fine.
Then consider the phrase "Unless you
specifically want to repeat the same sequence" above.


Which clearly no one on this thread /does/ want.


There are perfectly legitimate reasons to repeat the same sequence for
some applications, and there's nothing necessarily stupid about doing
so. That's why the standard specifies that behavior. Your
introduction of the word "stupidly" was, shall we say, less than
illuminating to the discussion.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 3 '06 #87
Micah Cowan <mi***@cowan.name> writes:
[...]
It was a comment on what he wrote. My point is that calling srand()
more than once /can/ have purposes beyond repeating the same sequence
of pseudo-random numbers, contrary to what Keith implied. Is no one on
this thread actually reading before they post?


I understood what you wrote, and I disagree with it (see my other
posts for more details).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 3 '06 #88
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
In article <44***************@spamcop.net>,
Kenneth Brody <ke******@spamcop.net> wrote:
Does the standard require that rand() return the same sequence each time
a program is run, if srand() is never called?


Yes, neglecting to call srand() is equivilent to using srand(1)
according to the C89 description of srand().


And C99.

(You can get your own PDF copy of the C99 standard plus TC1 and TC2;
google "n1124.pdf".)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 3 '06 #89
Pedro Graca wrote:
[thread hijack]

Does the standard guarantee the output of this program is the same on
all implementations (that have stdlib.h)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
printf("%d\n", rand());
srand(42);
printf("%d\n", rand());
return 0;
}

On my system (I don't have a compiler for my other OS here at home)
it outputs these numbers:

1804289383
71876166


No. However, it should produce the same output every time on your
implementation.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Mar 3 '06 #90
Walter Roberson wrote:
In article <sl*******************@ID-203069.user.individual.net>,
Pedro Graca <he****@hotpop.com> wrote:


Why copy the "Reply-To:" address and not the "From:" one?

It's ok :)
If I didn't want the address public I wouldn't use it; I just found it
strange to see this old address in a new post and thought my
configuration was messed up :)

--
If you're posting through Google read <http://cfaj.freeshell.org/google>
Mar 3 '06 #91
On Thu, 02 Mar 2006 23:26:07 GMT, Micah Cowan <mi***@cowan.name>
wrote:
>

Perhaps you should not have made it appear to be a comment on what
Keith wrote, then. I thought you intended something more than just a
random injection of a truism.


It was a comment on what he wrote. My point is that calling srand()
more than once /can/ have purposes beyond repeating the same sequence
of pseudo-random numbers, contrary to what Keith implied. Is no one on
this thread actually reading before they post?


Don't assume that those who don't agree with you just aren't reading
properly. I understand what Rod (and apparently you) is suggesting, I
just don't agree. I do agree with Keith (and others) that restarting
the sequence is as least as likely to decrease randomness as improve
it. I also agree that if staying with the same seed isn't random
enough for your purposes, then you need a better generator, rather
than repeatedly poking at the one you've got. Calling srand() multiple
times can only complicate the analysis.

--
Al Balmer
Sun City, AZ
Mar 3 '06 #92
Micah Cowan <mi***@cowan.name> wrote in
news:87************@mcowan.barracudanetworks.com:
Al Balmer <al******@att.net> writes:
On Thu, 02 Mar 2006 21:46:46 GMT, Micah Cowan <mi***@cowan.name>
wrote:
>Al Balmer <al******@att.net> writes:
>
>> On Thu, 02 Mar 2006 21:23:29 GMT, Micah Cowan <mi***@cowan.name>
>> wrote:
>>
>> >Keith Thompson <ks***@mib.org> writes:
>> >
>> >> Micah Cowan <mi***@cowan.name> writes:
>> >> > Keith Thompson <ks***@mib.org> writes:
>> >> Unless you specifically want to repeat the same sequence of
>> >> pseudo-random numbers, you should call rand() exactly once,
>> >> before any calls to rand().
>> >
>> >(You meant srand() instead of the first rand())
>> >
>> >Calling srand() more than once will not repeat the same sequence
>> >of pseudo-random numbers, unless you stupidly provide it with the
>> >same input as the last time. I'm fairly certain Rod intended that
>> >you call it each time with a time-based value.
>> >
>> s/stupidly/intentionally.
>
>No; srand() will repeat the same sequence of pseudo-random numbers,
>whether you did it intentionally or stupidly, so I think my original
>phrasing is fine.
> Perhaps you should not have made it appear to be a comment on what
Keith wrote, then. I thought you intended something more than just a
random injection of a truism.


....
I don't agree, generally, with what Rod's suggesting, but I was trying
to at least clarify that his point was rather different from what was
being claimed by others (Sinan still seems confused, at least), and
What am I confused about?

1) Calling srand multiple times in the program is only appropriate if it
is called with the same value each time so as to repeat a random
sequence (say, if you are running a simulation).

2) Calling srand multiple times with different values, on the other
hand, is a sure sign of confusion.
could actually be good advice in some very limited situations (in
applications such as he described [card games] and with /extremely/
poor PRNGs, or a very long-lived card player ;-) ).


If the RNG is that poor, one should use another one, rather than trying
to play tricks with srand.

The main reason srand exists is to provide repeatable results in
scientific applications.

Sinan
--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)
Mar 3 '06 #93
Micah Cowan <mi***@cowan.name> wrote in
news:87************@mcowan.barracudanetworks.com:
Calling srand() more than once will not repeat the same sequence of
pseudo-random numbers, unless you stupidly provide it with the same
input as the last time.


ITYM 'scientifically'. In science, replicability of results is crucial.

Sinan
--
A. Sinan Unur <1u**@llenroc.ude.invalid>
(reverse each component and remove .invalid for email address)
Mar 3 '06 #94
Keith Thompson <ks***@mib.org> writes:
Micah Cowan <mi***@cowan.name> writes:
If that doesn't give you good results, the solution
is to use a different pseudo-random number generator, not to call
srand() more than once.


I don't see how that follows.


It doesn't follow as a matter of rigorous deductive reasoning, but it
seems to me to be a reasonable common-sense inference. Any decent
pseudo-random number generator is going to be designed to work best
when it's allowed to generate a sequence from a starting seed without
interference. If you try to second-guess the algorithm by arbitrarily
perturbing it with additional calls to srand(), there is no reason to
think that the result is going to be any better (whatever "better"
means). If you *know* that re-seeding the algorithm will generate
better results, that implies, I think, that the algorithm is
defective, and you should just use a better one (many are freely
available). A re-seeding scheme that improves one RNG is unlikely to
improve another RNG, so any code that does something like this is
going to be gratuitously non-portable anyway. Using a different RNG
doesn't even sacrifice portability; numerous RNGs are available in
portable C code.


I think the above is extremely well put.
Mar 3 '06 #95
Keith Thompson <ks***@mib.org> writes:
Micah Cowan <mi***@cowan.name> writes:
Al Balmer <al******@att.net> writes:
On Thu, 02 Mar 2006 21:23:29 GMT, Micah Cowan <mi***@cowan.name>
wrote: [...] >Calling srand() more than once will not repeat the same sequence of
>pseudo-random numbers, unless you stupidly provide it with the same
>input as the last time. I'm fairly certain Rod intended that you call
>it each time with a time-based value.
>
s/stupidly/intentionally.
No; srand() will repeat the same sequence of pseudo-random numbers,
whether you did it intentionally or stupidly, so I think my original
phrasing is fine.
Then consider the phrase "Unless you
specifically want to repeat the same sequence" above.


Which clearly no one on this thread /does/ want.


There are perfectly legitimate reasons to repeat the same sequence for
some applications, and there's nothing necessarily stupid about doing
so.


Absolutely.
That's why the standard specifies that behavior. Your
introduction of the word "stupidly" was, shall we say, less than
illuminating to the discussion.


What I mean is, it would be stupid to do so in the context we've been
talking about. I'm sorry if it came across otherwise.

To be as clear as possible, what I meant is: if one proposes to call
srand() multiple times throughout a program's lifetime for the purpose
of "improving randomness", then doing so with the same input each time
would be stupid; however, doing so with different inputs wouldn't
necessarily be a terrible idea in some limited situations.

It's obviously not stupid to call srand() with the same input to
reproduce a given sequence, and I did not mean to suggest so.
Mar 3 '06 #96
"A. Sinan Unur" <1u**@llenroc.ude.invalid> writes:
Micah Cowan <mi***@cowan.name> wrote in
I don't agree, generally, with what Rod's suggesting, but I was trying
to at least clarify that his point was rather different from what was
being claimed by others (Sinan still seems confused, at least), and


What am I confused about?


From the posts that I've read, and from your recently posted code
(upstream), you were making a case against calling srand() (or more
accurately, after) each call to rand(). However, to my knowledge,
nobody was making a case /for/ such behavior.
1) Calling srand multiple times in the program is only appropriate if it
is called with the same value each time so as to repeat a random
sequence (say, if you are running a simulation).
I think everyone's agreeing here.
2) Calling srand multiple times with different values, on the other
hand, is a sure sign of confusion.
could actually be good advice in some very limited situations (in
applications such as he described [card games] and with /extremely/
poor PRNGs, or a very long-lived card player ;-) ).
If the RNG is that poor, one should use another one, rather than trying
to play tricks with srand.


Yes, that would be my preference as well. I would personally never do
as Rod has suggested; I was only trying to point out that he wasn't
completely without a point.
The main reason srand exists is to provide repeatable results in
scientific applications.


Hm. Given rand()'s implementation track-record, I can't think of many
scientific applications in which I would be comfortable using it
(though I don't doubt for a moment the truth of what you say).

OTOH, I have made frequent use of it when writing games. :-)
Mar 3 '06 #97
Micah Cowan <mi***@cowan.name> writes:
Keith Thompson <ks***@mib.org> writes:

[...]
There are perfectly legitimate reasons to repeat the same sequence for
some applications, and there's nothing necessarily stupid about doing
so.


Absolutely.
That's why the standard specifies that behavior. Your
introduction of the word "stupidly" was, shall we say, less than
illuminating to the discussion.


What I mean is, it would be stupid to do so in the context we've been
talking about. I'm sorry if it came across otherwise.

To be as clear as possible, what I meant is: if one proposes to call
srand() multiple times throughout a program's lifetime for the purpose
of "improving randomness", then doing so with the same input each time
would be stupid; however, doing so with different inputs wouldn't
necessarily be a terrible idea in some limited situations.

It's obviously not stupid to call srand() with the same input to
reproduce a given sequence, and I did not mean to suggest so.


Agreed, and again, thanks for the clarification.

Just to be even clearer, I don't recall anyone suggesting that srand()
should be called again with the same seed for the purpose of improving
randomness (though someone may well have have mistakenly thought that
someone else had suggested it).

Which is not intended to suggest that *you* necessarily suggested that
anyone had suggested it, merely that <POOF> oh, crud, there goes my
last brain cell.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Mar 3 '06 #98
Pedro Graca wrote:

[thread hijack]

Does the standard guarantee the output of this program is the
same on all implementations (that have stdlib.h)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
printf("%d\n", rand());
srand(42);
printf("%d\n", rand());
return 0;
}

On my system (I don't have a compiler for my other OS here at
home) it outputs these numbers:

1804289383
71876166


No such guarantee. If you want a completely controlled random
generator, supply your own. For an example of this, see the test
program for my hashlib package, which uses a Mersenne Twister
generator. That way I can supply regression tests by comparing
tester output with my own output.

<http://cbfalconer.home.att.net/download/hashlib.zip>

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell.org/google/>
Also see <http://www.safalra.com/special/googlegroupsreply/>
Mar 3 '06 #99
In article <sl*******************@ID-203069.user.individual.net>,
Pedro Graca <he****@hotpop.com> wrote:
Walter Roberson wrote:
In article <sl*******************@ID-203069.user.individual.net>,
Pedro Graca <he****@hotpop.com> wrote:
Why copy the "Reply-To:" address and not the "From:" one?


It was automatic by my newsreader. I'd guess it picks that one
as part of the same logic that prepares the address for Cc:
or email reply purposes.
--
Prototypes are supertypes of their clones. -- maplesoft
Mar 3 '06 #100

This discussion thread is closed

Replies have been disabled for this discussion.

By using this site, you agree to our Privacy Policy and Terms of Use.