473,583 Members | 3,114 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Init random numbers with time?

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 sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers? Probably based on
milliseconds instead of seconds? And integrating the process ID or
current amount of free memory or whatever? Is there a C++ library that
does it right?

Here is the program that outputs 3 different random numbers on a
../a.out call, but two identical sequences if called in a row like:
../a.out; ./a.out

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main(){
srand((unsigned )time(0));
for(unsigned i=0; i<3; ++i){
cout << rand() << endl;
}
cout << endl;
return EXIT_SUCCESS;
}

Thanks!
Markus

Dec 5 '06 #1
16 8777
On Mon, 04 Dec 2006 21:43:37 -0800, Markus Dehmann wrote:
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 sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers?
Yes, if you want different behavior on every run. Though you may prefer
identical behavior on every run for certain phases of testing.
Probably based on
milliseconds instead of seconds?
There isn't a standard function that's guaranteed to return milliseconds.
There's nothing in the standard that time_t can't be in milliseconds, or
that it must be. You're dealing with inherently OS-specific functionality.
And integrating the process ID or
current amount of free memory or whatever?
Is your idea that by adding PID you would get distinct sequences when the
program is run more than once in the same second? That'd probably work,
except that getting the PID is also a non-portable construct. You might
as well just used the fine-grained OS-specific time function. I know of
at least one OS in which the time function is guaranteed to return unique
values on every call. And there are OSes that don't have PIDs. So your
proposal would be unnecessary on some, and impossible on others.
Is there a C++ library that
does it right?
"Right" is a matter of opinion. IMO, a pseudo-random generator that can't
be configured to produce repeatable sequences when desired is broken. In
other words, if you want to initialize the seed from the system clock, do
so.
Here is the program that outputs 3 different random numbers on a
./a.out call, but two identical sequences if called in a row like:
./a.out; ./a.out

[...]
--
"The national budget must be balanced. The public debt must be
reduced; the arrogance of the authorities must be moderated and
controlled. Payments to foreign governments must be reduced,
if the nation doesn't want to go bankrupt. People must again
learn to work, instead of living on public assistance."
- Marcus Tullius Cicero

Dec 5 '06 #2
Markus Dehmann <ma************ @gmail.comwrote :
>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 sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers? Probably based on
milliseconds instead of seconds?
One approach is to use the process id as part of the seed. One
standard/portable way to do this is to use an integer hash function
of the string returned by tmpnam().

Steve
Dec 5 '06 #3
On 4 Dec 2006 21:43:37 -0800 in comp.lang.c++, "Markus Dehmann"
<ma************ @gmail.comwrote ,
>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 sequence on every program call
if the program is called several times in a second!
Indeed, that method is unsuitable for a program that's going to be
called several times in a second. It may also be unsuitable for a
program that's going to be launched by "chron" or the windows task
scheduler etc. at repeated predictable times. The whole rand()
scheme is suitable for only casual undemanding applications.

For a somewhat better grade of random numbers I think I'd start by
adapting the random number generator class from Stroustrup ch. 22.
For your concern, I'd make it a class that loaded the seed from a file
in the constructor and saved it back to disk in the destructor.

For the best grade of random numbers, consult a cryptologist.

In June 1998 the Arizona Lottery had to suspended its Pick 3 game when
they discovered that their random number generator selecting the winning
numbers never picked the digit 9. (RISKS Digest 19.3)
Dec 5 '06 #4
On Tue, 05 Dec 2006 06:03:37 GMT in comp.lang.c++, David Harmon
<so****@netcom. comwrote,
>In June 1998 the Arizona Lottery had to suspended its Pick 3 game when
they discovered that their random number generator selecting the winning
numbers never picked the digit 9. (RISKS Digest 19.3)
Sorry, that's RISKS Digest 19.83

Dec 5 '06 #5
I wrote:
>One approach is to use the process id as part of the seed. One
standard/portable way to do this is to use an integer hash function
of the string returned by tmpnam().
I notice the gcc documentation for tmpnam() says: "Never use this
function. Use mkstemp(3) instead".

However, mkstemp() is not part of standard C++, whereas tmpnam()
is, so pick your poison.

Steve
Dec 5 '06 #6
On Dec 5, 6:43 am, "Markus Dehmann" <markus.dehm... @gmail.comwrote :
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 sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers? Probably based on
milliseconds instead of seconds? And integrating the process ID or
current amount of free memory or whatever? Is there a C++ library that
does it right?
As many have pointed out, if you want to do this well, you'll have to
use some platform-specific code (or wait to the next version of the
standard, looks like it will have random number generators). If you are
running Linux/Unix you can read in a value to use as seed from
/dev/random (or dev/urandom or something such). This will give you
high-entropy random numbers.

--
Erik Wikström

Dec 5 '06 #7
lwz
You could put a random number generated by rand() into your srand
function, maybe even added to the number of processor clock ticks after
the process started (clock())... so
srand(rand()+cl ock()+time(NULL ));

er****@student. chalmers.se wrote:
On Dec 5, 6:43 am, "Markus Dehmann" <markus.dehm... @gmail.comwrote :
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 sequence on every program call
if the program is called several times in a second! Isn't there a
better method to seed the random numbers? Probably based on
milliseconds instead of seconds? And integrating the process ID or
current amount of free memory or whatever? Is there a C++ library that
does it right?

As many have pointed out, if you want to do this well, you'll have to
use some platform-specific code (or wait to the next version of the
standard, looks like it will have random number generators). If you are
running Linux/Unix you can read in a value to use as seed from
/dev/random (or dev/urandom or something such). This will give you
high-entropy random numbers.

--
Erik Wikström
Dec 5 '06 #8
On Tue, 05 Dec 2006 02:42:11 -0800, lwz wrote:
You could put a random number generated by rand() into your srand
function, maybe even added to the number of processor clock ticks after
the process started (clock())... so
srand(rand()+cl ock()+time(NULL ));
That's not going to give you a unique seed, if you start the program
multiple times in the same second. Calling rand() without having set a
distinct seed will always return the same value. On many platforms,
calling clock() at the same point in program execution will always return
the same value.

--
Windows2000 - from the people who brought you edlin.

Dec 5 '06 #9
Hi

Steve Pope wrote:
I wrote:
>>One approach is to use the process id as part of the seed. One
standard/portable way to do this is to use an integer hash function
of the string returned by tmpnam().

I notice the gcc documentation for tmpnam() says: "Never use this
function. Use mkstemp(3) instead".
It's completely safe if you just want to use the string for whatever
purpose. The only problem with the function is that getting the filename
from tmpnam and actually opening the file is not atomic, which leaves you
vulnerable to some attacks:
http://www.owasp.org/index.php/Insecure_Temporary_File

Markus

Dec 5 '06 #10

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

Similar topics

10
11941
by: Nicholas Geraldi | last post by:
Im looking for a decent random number generator. Im looking to make a large number of random numbers (100 or so, if not more) in a short period of time (as fast as possible). the function i was using to get random numbers was Random rn = new Random(System.currentTimeMillis()); but it seems that the system doesn't update the milliseconds...
10
2492
by: Virus | last post by:
Ok well what I am trying to do is have 1.) the background color to change randomly with 5 different colors.(change on page load) 2,) 10 different quotes randomly fadeing in and out in random spots on the webpage. with a delay timer on them, so they keep changing as the page is open. Not random each time the page is loaded. If anyone...
3
7370
by: Joe | last post by:
Hi, I have been working on some code that requires a high use of random numbers within. Mostly I either have to either: 1) flip a coin i.e. 0 or 1, or 2) generate a double between 0 and 1. I have utilised the following random number source code http://www.agner.org/random/ What I have found is that there is a problem with seeding. The...
1
30908
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. --------------------------------------------- #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv)
23
2269
by: Alvin | last post by:
Well, I'm developing a Tetris game in SDL, but when it comes to deciding the next block, I'm stuck. It's random, but when I try something like seeding the randomizer with the time, it won't update as fast as one block can fall, and the next to be determined. Generating different numbers in one spur can work, but people can play Tetris for...
104
5107
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...
22
3420
by: gagan.singh.arora | last post by:
Hi there. I want to generate random numbers with a given probability, say 80% even and 20% odd. Is it possible to implement such an algorithm in C?
13
2790
by: Peter Oliphant | last post by:
I would like to be able to create a random number generator that produces evenly distributed random numbers up to given number. For example, I would like to pick a random number less than 100000, or between 0 and 99999 (inclusive). Further, the I want the range to be a variable. Concretely, I would like to create the following method: ...
24
7196
by: pereges | last post by:
I need to generate two uniform random numbers between 0 and 1 in C ? How to do it ? I looked into rand function where you need to #define RAND_MAX as 1 but will this rand function give me uniformly distributed and unique numbers ?
0
7896
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...
0
7827
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8328
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...
0
8195
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...
0
6581
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...
1
5701
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...
0
3820
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3845
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2334
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.