473,786 Members | 2,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

rand - is RAND_MAX how long before the same # will occur again?

When I use rand(), is the RAND_MAX value how long I am guaranteed that
the same value will not appear twice?

And is this a floating window?

For example, if RAND_MAX is 32767, and I make 500,000 consecutive rand
calls then is the rand() algorithm going to guarantee me that no
floating window of calls over that 500,000 rand calls will have the
same value twice? The only way that would work is if the series was
identical everytime.

I just found some code that someone wrote that uses rand() to create a
unique id, and I'm thinking it would make more sense just to take a 32
bit int, and increment it everytime with a conditional check that
restarts it at 1 when the max value for the int is reached. I cannot
see any obvious reason why rand() was used instead of this approach.

Nov 14 '05 #1
8 4394
"Jack" <js*********@ya hoo.com> writes:
When I use rand(), is the RAND_MAX value how long I am guaranteed that
the same value will not appear twice?


No. It is very unlikely that no value will appear twice. If the
random number generator is uniformly random, the chance that no
value will appear twice in RAND_MAX calls, assuming RAND_MAX ==
32767, is

(32766 / 32767) * (32765 / 32767) * ... * (1 / 32767)
== 32766! / (32767)**32766
~= 1.347 * 10**-14228 (according to Emacs calc)

This result is much, much smaller than the maximum value for
LDBL_MIN.

(Someone should check my math, I'm not so good at this. Also,
smartasses, the above are math formulas, not C expressions.)
--
"What is appropriate for the master is not appropriate for the novice.
You must understand the Tao before transcending structure."
--The Tao of Programming
Nov 14 '05 #2
On 29 Jan 2005 08:51:11 -0800, "Jack" <js*********@ya hoo.com> wrote:
When I use rand(), is the RAND_MAX value how long I am guaranteed that
the same value will not appear twice?
No, if the numbers are random then it is entirely possible for the
first two to be the same.

RAND_MAX is simply the largest value that rand can return.

And is this a floating window?
What is a floating window?

For example, if RAND_MAX is 32767, and I make 500,000 consecutive rand
calls then is the rand() algorithm going to guarantee me that no
floating window of calls over that 500,000 rand calls will have the
same value twice? The only way that would work is if the series was
identical everytime.
I don't know what you mean here but if you make 500,000 calls then on
average each value will occur 16-17 times.

I just found some code that someone wrote that uses rand() to create a
unique id, and I'm thinking it would make more sense just to take a 32
bit int, and increment it everytime with a conditional check that
restarts it at 1 when the max value for the int is reached. I cannot
see any obvious reason why rand() was used instead of this approach.


Ask the author.
<<Remove the del for email>>
Nov 14 '05 #3
"Jack" writes:
I just found some code that someone wrote that uses rand() to create a
unique id, and I'm thinking it would make more sense just to take a 32
bit int, and increment it everytime with a conditional check that
restarts it at 1 when the max value for the int is reached. I cannot
see any obvious reason why rand() was used instead of this approach.


My guess: the author goofed, it's a relatively easy mistake to make. A
reason that has at least *some* plausibility: Information hiding, he didn't
want the users to glean any information from their relative numbers.
Nov 14 '05 #4
Ben Pfaff wrote:
"Jack" <js*********@ya hoo.com> writes:

When I use rand(), is the RAND_MAX value how long I am guaranteed that
the same value will not appear twice?

No. It is very unlikely that no value will appear twice. If the
random number generator is uniformly random, the chance that no
value will appear twice in RAND_MAX calls, assuming RAND_MAX ==
32767, is

(32766 / 32767) * (32765 / 32767) * ... * (1 / 32767)
== 32766! / (32767)**32766
~= 1.347 * 10**-14228 (according to Emacs calc)

This result is much, much smaller than the maximum value for
LDBL_MIN.

(Someone should check my math, I'm not so good at this. Also,
smartasses, the above are math formulas, not C expressions.)


FWIW, a different tool gives me the same result. If we're
wrong, I at least am in good company.

However, this calculation assumes successive rand() values
are independent, which is certainly not the case. rand() is
required to be deterministic in the sense that it produces the
exact same sequence of values for a given explicit or implied
srand() argument; the srand() argument completely determines
the sequence of subsequent rand() values.

Drifting into implementation specifics, it is also worth
noting that if rand() is a full-period linear congruential
generator it produces a permutation of { 0 .. RAND_MAX }, so
the probability of a repeated value in RAND_MAX calls or even
in RAND_MAX+1 calls is zero! Of course, the probability of a
repetition in RAND_MAX+2 calls rises abruptly to unity. For
a pure multiplicative generator with prime modulus, the generated
values are a permutation of { 1 .. RAND_MAX } and the probability
transition lies between RAND_MAX and RAND_MAX+1 calls.

For the benefit of the O.P. (Ben already knows this), the
Standard does not specify what algorithm underlies rand(), and
different implementations use different generators. It is
certainly an error to assume that rand() will not repeat itself
within RAND_MAX calls; it is even possible that two rand() calls
in a row can return the same value.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #5
"Jack" <js*********@ya hoo.com> writes:
When I use rand(), is the RAND_MAX value how long I am guaranteed that
the same value will not appear twice?
You're not. If the values returned by rand() were truly random, there
would be a 1.0/(RAND_MAX+1) chance that two successive calls to rand()
would yield the same value.

Of course rand() returns pseudo-random values, and the sequence is
required to be reproducible for a given seed (the argument passed to
srand().

If the internal state is no bigger than the value returned (e.g., if
RAND_MAX is 32767 and the system stores only 15 bits of internal
state), then rand() can never return the same result twice -- if it
did, it would continue to return that same result indefinitely. In
that case, the results will repeat with a cycle of *at most*
RAND_MAX+1.

If it keeps a larger internal state, the results are going to look
more like real random numbers, though of course they'll still be
deterministic. For example, if there are 1024 bits of internal state,
that makes 2**1024 possible states; srand() lets you select one of
UINT_MAX+1 of those states.

So, depending on the implementation, two successive calls to rand()
might never return the same value, or they might do so once in
RAND_MAX+1 calls (periodically or probabilistical ly), or they might do
something else if the implementation is more "pseudo" than "random".

[snip]
I just found some code that someone wrote that uses rand() to create a
unique id, and I'm thinking it would make more sense just to take a 32
bit int, and increment it everytime with a conditional check that
restarts it at 1 when the max value for the int is reached. I cannot
see any obvious reason why rand() was used instead of this approach.


If all you care about is uniqueness, incrementing a variable is easier
and more effective than using rand(). If you also want
unpredictabilit y, you can use a random number, but you have to allow
for the possibility of repeated values, probably by keeping track of
all the ids you've already used. RAND_MAX can be as small as 32767,
so it's not useful if you want a large number of unique ids. Finally,
rand() is often not very good, and can be easy to predict if you know
the algorithm; it's almost certainly not suitable for cryptographic
applications.

--
Keith Thompson (The_Other_Keit h) 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.
Nov 14 '05 #6
Eric Sosman wrote:
It is
certainly an error to assume that rand() will not repeat itself
within RAND_MAX calls; it is even possible that two rand() calls
in a row can return the same value.


It is even possible that *all* rand() calls can return the same value.

--
pete
Nov 14 '05 #7
pete <pf*****@mindsp ring.com> writes:
Eric Sosman wrote:
It is
certainly an error to assume that rand() will not repeat itself
within RAND_MAX calls; it is even possible that two rand() calls
in a row can return the same value.


It is even possible that *all* rand() calls can return the same value.


C99 7.20.2p2:

The rand function computes a sequence of pseudo-random integers in
the range 0 to RAND_MAX.

I don't think you can stretch the meaning of "pseudo-random" to
include a repeated sequence of the same value.

(On the other hand, if it generated truly random values, there would
be a finite probability that it could produce an arbitrarily long
sequence of a single value.)

--
Keith Thompson (The_Other_Keit h) 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.
Nov 14 '05 #8
Keith Thompson wrote:

pete <pf*****@mindsp ring.com> writes:
Eric Sosman wrote:
It is
certainly an error to assume that rand() will not repeat itself
within RAND_MAX calls; it is even possible that two rand() calls
in a row can return the same value.


It is even possible that *all* rand() calls can return the same value.


C99 7.20.2p2:

The rand function computes a sequence of pseudo-random integers in
the range 0 to RAND_MAX.

I don't think you can stretch the meaning of "pseudo-random" to
include a repeated sequence of the same value.

(On the other hand, if it generated truly random values, there would
be a finite probability that it could produce an arbitrarily long
sequence of a single value.)


It's a quality of implementation issue,
like a malloc that always returns NULL.
There's nothing in the standard which prohibits
a very poor quality rand().

--
pete
Nov 14 '05 #9

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

Similar topics

36
2695
by: Profetas | last post by:
Hi, I want to generate a random 8 bit number using rand(0 is that possible? to expecifu the base and the lenght? thanks
4
5761
by: Bill Burris | last post by:
Hi, With VS .NET 2003 the rand() function sometimes returns a number equal to RAND_MAX. The docs say: The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. Does this mean that 0 & RAND_MAX are included in the range? I am asking because I was using code from a book, which was developed on Linux. The program occasionally dies, because the random number is used in calculating an array index. It seems that the...
10
2349
by: Frank Silvermann | last post by:
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define MIN_WORD_LENGTH 9
26
4110
by: Gary Wessle | last post by:
Hi I need help to generate some random numbers between 2 and 8. #include <cstdlib> using std::rand; the following was out of my range, int main() {
13
3671
by: Spiros Bousbouras | last post by:
The standard says that rand() should return a pseudo-random number but what does pseudorandom mean ? If an implementation of rand() always returned the same number would it be conforming ? What if it always alternated between 2 values ? On the practical side do you have any thoughts on what one could realistically expect from the behaviour of rand() ? Could for example one expect that eventually any value in the range will be returned ?
17
2209
by: kkirtac | last post by:
Hello, i m using the standard rand() function to generate several random numbers. Even if i seed the generator before the loop "srand( (unsigned)time( NULL ) );" , it usually selects a previously selected number in the process, after 6-7 iterations, i want the sequence to be unique..should i consider some further modifications in the code to achieve my goal maybe ? here is the piece of code.. vector<intrands ; int rnd ; //random number...
10
3021
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
8
4730
by: remlostime | last post by:
i use g++ to generater rand number, now i find that the RAND_MAX is 32367 in my computer, how can i make a bigger rand number( the number is wihin in the integer(2^32-1))
15
3947
by: Rich Fife | last post by:
Quick rand() question: I know you're not supposed to use "rand() % 1024" for instance, because it focuses on the lower bits. However, it seems to me that given that the argument is not a power of two (or near a power of two), that this is not an issue. The upper bits will participate equally in the result with the lower. Am I missing something? Thanks!
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10360
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10163
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10108
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5397
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4064
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
2
3668
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.