473,387 Members | 1,664 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

time and srand

What kind of problems could arise if
one were to not cast the value of time()
to unsigned int? What are the sections
in the standard that provide the reasoning
of any claims against such a practice?

--
conrad
Dec 20 '07 #1
16 3305
conrad wrote:
What kind of problems could arise if
one were to not cast the value of time()
to unsigned int? What are the sections
in the standard that provide the reasoning
of any claims against such a practice?
The cast is recommended since there is no implicit conversion between
unsigned and time_t. The C standard simply says that time_t is an
arithmetic type. It could be an integer or floating point type.
Therefore an explicit cast is usual when using a time_t value as seed
for srand.

Dec 20 '07 #2
santosh said:
conrad wrote:
>What kind of problems could arise if
one were to not cast the value of time()
to unsigned int? What are the sections
in the standard that provide the reasoning
of any claims against such a practice?

The cast is recommended
No, it isn't.

See
http://groups.google.com/group/comp....316d326af97ad6

or, if that doesn't work and you trust me enough, see
http://tinyurl.com/2ur3c3

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Dec 20 '07 #3
santosh <sa*********@gmail.comwrites:
conrad wrote:
>What kind of problems could arise if
one were to not cast the value of time()
to unsigned int? What are the sections
in the standard that provide the reasoning
of any claims against such a practice?

The cast is recommended since there is no implicit conversion between
unsigned and time_t. The C standard simply says that time_t is an
arithmetic type. It could be an integer or floating point type.
Therefore an explicit cast is usual when using a time_t value as seed
for srand.
Yes, there is an implicit conversion from unsigned to time_t, as there
is between any two arithmetic types.

This:
srand(time(NULL));
and this:
srand((unsigned)time(NULL));
are equivalent, assuming you have the required "#include <time.h>".
Since the cast doesn't buy you anything, you might as well leave it
out.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 20 '07 #4
James Kuyper wrote:
conrad wrote:
>What kind of problems could arise if
one were to not cast the value of time()
to unsigned int? What are the sections
in the standard that provide the reasoning
of any claims against such a practice?

I can't see any plausible problems with not casting the value of
time() to an unsigned int.

I do see possible problems from casting it to unsigned int:
<snip>

In light of your, Keith's, and Richard's reply I apologise to the OP for
incorrect advice.

Dec 20 '07 #5
Keith Thompson wrote:
James Kuyper <ja*********@verizon.netwrites:
....
Who suggested to you that conversion to unsigned int was the proper
thing to do, and what reasons did they give?

The context, I think was
srand(time(NULL));
Since srand's argument is of type unsigned int, the conversion will
happen with or without a cast.
Depending upon the implementation-specific time representation used
for time_t, that expression might generate only a small number of
different seed values, or it might generate seed values that change
excessively slowly with time. What you typically need in that context
is an expression that generates a different seed value each time you
run the program, and has a roughly equal chance of generating every
permitted seed value.

To minimize dependence upon the representation of time_t, I'd
recommend something like this:

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

srand(fmod(difftime(0, time(NULL), UINT_MAX+1.0));

That will use different seed values at the rate of 1/second, which
should be good enough for many purposes.
Dec 20 '07 #6
On Dec 20, 2:06 pm, jameskuy...@verizon.net wrote:
Keith Thompson wrote:
James Kuyper <jameskuy...@verizon.netwrites:
...
Who suggested to you that conversion to unsigned int was the proper
thing to do, and what reasons did they give?
The context, I think was
srand(time(NULL));
Since srand's argument is of type unsigned int, the conversion will
happen with or without a cast.

Depending upon the implementation-specific time representation used
for time_t, that expression might generate only a small number of
different seed values, or it might generate seed values that change
excessively slowly with time. What you typically need in that context
is an expression that generates a different seed value each time you
run the program, and has a roughly equal chance of generating every
permitted seed value.

To minimize dependence upon the representation of time_t, I'd
recommend something like this:

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

srand(fmod(difftime(0, time(NULL), UINT_MAX+1.0));

That will use different seed values at the rate of 1/second, which
should be good enough for many purposes.
I was thinking too hard; the fmod() is unnecessary, of course.
Dec 20 '07 #7
ja*********@verizon.net said:

<snip>
To minimize dependence upon the representation of time_t, I'd
recommend something like this:

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

srand(fmod(difftime(0, time(NULL), UINT_MAX+1.0));
Lawrence Kirby once proposed the following alternative, which works very
nicely:

#include <limits.h>
#include <stdlib.h>
#include <time.h>
/* Choose and return an initial random seed based on the current time.
Based on code by Lawrence Kirby <f...@genesis.demon.co.uk>.
Usage: srand (time_seed ()); */
unsigned
time_seed (void)
{
time_t timeval; /* Current time. */
unsigned char *ptr; /* Type punned pointed into timeval. */
unsigned seed; /* Generated seed. */
size_t i;
timeval = time (NULL);
ptr = (unsigned char *) &timeval;
seed = 0;
for (i = 0; i < sizeof timeval; i++)
seed = seed * (UCHAR_MAX + 2u) + ptr[i];
return seed;
}

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Dec 20 '07 #8

<ja*********@verizon.netwrote in message
news:f9**********************************@f3g2000h sg.googlegroups.com...
Keith Thompson wrote:
>James Kuyper <ja*********@verizon.netwrites:
...
Who suggested to you that conversion to unsigned int was the proper
thing to do, and what reasons did they give?

The context, I think was
srand(time(NULL));
Since srand's argument is of type unsigned int, the conversion will
happen with or without a cast.

Depending upon the implementation-specific time representation used
for time_t, that expression might generate only a small number of
different seed values, or it might generate seed values that change
excessively slowly with time. What you typically need in that context
is an expression that generates a different seed value each time you
run the program, and has a roughly equal chance of generating every
permitted seed value.

To minimize dependence upon the representation of time_t, I'd
recommend something like this:

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

srand(fmod(difftime(0, time(NULL), UINT_MAX+1.0));

That will use different seed values at the rate of 1/second, which
should be good enough for many purposes.
one option I have used:
implement a custom prng, with a larger internal state, for example, 4096
bits (reason: rand does not necissarily have all that large of an internal
state, and is thus not really good for some uses);
the initialization function can load the seed from a file, use the 'time'
trick, rehash the seed or similar, and store it back out to the file (thus
each run hopefully adding a little more entropy).

if done well, with any luck, this gives at least some semblence of
randomness.

rand is useful for some things (where the actual randomness isn't all that
important, or only applies to a small range).

but, when using it for some other things, for example, generating largish
presumably unique values (GUID-like values, ...) one hopes for something
hopefully a little more 'random'.

for example, if it only has about 32 or 48 bits of entropy, what good is it
to try to generate , say, 96 bit unique values. there will be, at most (and
probably much less) 2^32 or 2^48 different values.

a slightly larger entropy, say, 2^4096, is a little more sane for this kind
of use.

or such...
now, here is another possibly interesting (mostly hypothetical) problem:
open-source copy protection.

goal: a copy protection scheme which will still work, even when the user has
full ability to look at, modify, and recompile the source (and, thus, it
can't be based on obscurity, or something which the user can simply bypass
or comment out).

I have some possible ideas here, but I will keep them to myself...

Dec 20 '07 #9
Jack Klein <ja*******@spamcop.netwrites:
On Thu, 20 Dec 2007 12:45:31 GMT, James Kuyper
<ja*********@verizon.netwrote in comp.lang.c:
[...]
>4. If time_t is an imaginary type, the conversion will loose 100% of the
information.

What exactly is an imaginary type in C? They only exist as part of a
_Complex float, double, or long double. They no more exist in
isolation than do quarks.
[...]

_Imaginary float, _Imaginary double, or _Imaginary long double.

See C99 Annex G (which is optional).

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 21 '07 #10
Jack Klein wrote:
On Thu, 20 Dec 2007 12:45:31 GMT, James Kuyper
<ja*********@verizon.netwrote in comp.lang.c:
....
3. If time_t is a floating point type, the conversion will loose you the
fractional part,

If time_t is a floating point type and the integral part of the value
is greater than UINT_MAX or less than 0, the conversion will generate
undefined behavior. With or without a cast.
For some reason I remembered incorrectly that the modulus rules for
conversion to unsigned types applied to floating point sources as
well. Since you are correct, that means that the fmod() in my other
message was indeed necessary.
Dec 21 '07 #11

"Keith Thompson" <ks***@mib.orgwrote in message
news:87************@kvetch.smov.org...
Jack Klein <ja*******@spamcop.netwrites:
>On Thu, 20 Dec 2007 12:45:31 GMT, James Kuyper
<ja*********@verizon.netwrote in comp.lang.c:
[...]
>>4. If time_t is an imaginary type, the conversion will loose 100% of the
information.

What exactly is an imaginary type in C? They only exist as part of a
_Complex float, double, or long double. They no more exist in
isolation than do quarks.
[...]

_Imaginary float, _Imaginary double, or _Imaginary long double.

See C99 Annex G (which is optional).
and, a few of us were lazy and ended up internally aliasing _Imaginary to
_Complex...

actually, at first I had implemented them as such, later noticing that GCC
had only _Complex, and thus I lacked some motivation on this front, and
later on _Complex effectively assimilated _Imaginary.
now, something even more weird:
in my upper compiler, since _Complex only applies to float types, and
'unsigned' only really applies to integer types, I ended up using the same
modifier for both (in this case, a flag).

so, in this case:
unsigned float f;
and:
float _Complex f;

come out as equivalent...
however, in the lower compiler, each type effectively has a unique type, so
there is no such aliasing at this level.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"

Dec 21 '07 #12
Followups set to comp.programming.

cr88192 wrote:
now, here is another possibly interesting (mostly hypothetical) problem:
open-source copy protection.

goal: a copy protection scheme which will still work, even when the user has
full ability to look at, modify, and recompile the source (and, thus, it
can't be based on obscurity, or something which the user can simply bypass
or comment out).
What is the goal of a copy protection scheme when the user has the ability
to look at, modify, and recompile the source? What, specifically, is being
protected from what?
I have some possible ideas here, but I will keep them to myself...
You can use a public-key-based signature to demonstrate that some
particular person has approved a particular version. That doesn't prevent
copying, though.

--
Thad
Dec 27 '07 #13
James Kuyper wrote:
4. If time_t is an imaginary type, the conversion will loose 100% of the
information.
That's an implementation I'd like to have!

--
Army1987 (Replace "NOSPAM" with "email")
Dec 30 '07 #14
On Sun, 30 Dec 2007 16:40:31 +0000 (UTC), Army1987
<ar******@NOSPAM.itwrote:
>James Kuyper wrote:
>4. If time_t is an imaginary type, the conversion will loose 100% of the
information.

That's an implementation I'd like to have!
For all the language pedantry in this group, you would think they
would be better spellers.

lose, not loose.

Simple mnemonic:

To lose is lost.
Too loose is a noose.
Dec 30 '07 #15
Geoff wrote:
On Sun, 30 Dec 2007 16:40:31 +0000 (UTC), Army1987
<ar******@NOSPAM.itwrote:
>James Kuyper wrote:
>>4. If time_t is an imaginary type, the conversion will loose 100% of the
information.
That's an implementation I'd like to have!

For all the language pedantry in this group, you would think they
would be better spellers.
Being pedantic about other people's mistakes doesn't mean that I don't
make mistakes of my own; it just means that it's annoying when I
discover that I've made one. Still, I prefer to know about my mistakes,
rather than remaining ignorant of them.
Dec 31 '07 #16

"James Kuyper" <ja*********@verizon.netwrote in message
news:F16ej.35549$NL5.33682@trnddc05...
Geoff wrote:
>On Sun, 30 Dec 2007 16:40:31 +0000 (UTC), Army1987
<ar******@NOSPAM.itwrote:
>>James Kuyper wrote:

4. If time_t is an imaginary type, the conversion will loose 100% of
the information.
That's an implementation I'd like to have!

For all the language pedantry in this group, you would think they
would be better spellers.

Being pedantic about other people's mistakes doesn't mean that I don't
make mistakes of my own; it just means that it's annoying when I discover
that I've made one. Still, I prefer to know about my mistakes, rather than
remaining ignorant of them.
No. Not so much.

Your error is in the quotation, where I find no misspelling other than your
spelling of "Jeff." I wrote an essay on it in second grade and didn't plan
a reprise. I was "Letterman."

c.l.c's leading miss speller has had more words recalled for things like "no
spaces" than anyone I know. Hey, Heathfield, who's your dumbass mi5 spam
..mer?
--
tja
and

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Jan 2 '08 #17

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

Similar topics

1
by: Wavelet | last post by:
If I use srand(value) to change the random seed, when I close the vc or run the code from the beginning, the seeds of random will change to default value or still keep the value of what I designed...
1
by: Intaek LIM | last post by:
generally, we use srand(time(0)) to generate random numbers. i know why we use time(0), but i can not explain how it operates. first, see example source below. ...
13
by: Jeremy Holdstadt | last post by:
This seems to be a C question to me. If it is not, I apologize. This command: awk 'BEGIN {srand();print srand()}' will give the number of seconds since the epoch, present time. Can any of you...
1
by: Alfonso Morra | last post by:
Hi I'm compiling some code and need to generate some random numbers. To save time, I decided to use the srand, rand and time functions. My code worked (atleast built fine) until I added time.h,...
16
by: Markus Dehmann | last post by:
According to several C++ tutorials, calling srand like this to initialize the random number generator seems to be standard: srand((unsigned)time(0)); But it leads to the same random number...
20
by: Bill Cunningham | last post by:
I am stumped on this one. I tried two methods and something just doesn't seem right. I'll try my new syle. #include <stdio.h> #include <stdlib.h> main() { srand(2000); /*seed unsigned */...
8
by: Ioannis Vranos | last post by:
Is srand(time(0)); an effective solution for seeding rand(), or is there any better approach?
31
by: Ioannis Vranos | last post by:
Regarding C95: Is srand(time(NULL)); an effective solution for seeding rand(), or is there any better approach?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
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,...
0
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
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,...
0
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...

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.