Download your favorite Linux distribution at LQ ISO.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 11-07-2005, 11:05 AM   #1
Registered: Dec 2004
Location: Vietnam (Việt Nam)
Distribution: Gentoo (desktop), Arch linux (laptop)
Posts: 728

Rep: Reputation: 33
Generate random number with C++

Hi all.
The question is simple and clear.
How can I generate a random number?
Old 11-07-2005, 11:16 AM   #2
Senior Member
Registered: Nov 2000
Location: Seattle, WA USA
Distribution: Ubuntu @ Home, RHEL @ Work
Posts: 3,892
Blog Entries: 1

Rep: Reputation: 67
You need to include cstdlib and then check out the srand/rand/rand_r functions.

RAND(3)                                         Linux Programmer's Manual                                         RAND(3)

       rand, rand_r, srand - pseudo-random number generator

       #include <stdlib.h>

       int rand(void);

       int rand_r(unsigned int *seedp);

       void srand(unsigned int seed);

       The rand() function returns a pseudo-random integer between 0 and RAND_MAX.

       The  srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by
       rand().  These sequences are repeatable by calling srand() with the same seed value.

       If no seed value is provided, the rand() function is automatically seeded with a value of 1.

       The function rand() is not reentrant or thread-safe, since it uses hidden state that is  modified  on  each  call.
       This  might  just be the seed value to be used by the next call, or it might be something more elaborate. In order
       to get reproducible behaviour in a threaded application, this state must be made explicit. The  function  rand_r()
       is supplied with a pointer to an unsigned int, to be used as state.  This is a very small amount of state, so this
       function will be a weak pseudo-random generator. Try drand48_r(3) instead.

       The rand() and rand_r() functions return a value between 0 and RAND_MAX.  The srand() function returns no value.

       POSIX 1003.1-2003 gives the following example of an implementation of rand() and srand(), possibly useful when one
       needs the same sequence on two different machines.

           static unsigned long next = 1;

           /* RAND_MAX assumed to be 32767 */
           int myrand(void) {
               next = next * 1103515245 + 12345;
               return((unsigned)(next/65536) % 32768);

           void mysrand(unsigned seed) {
               next = seed;

       The  versions  of  rand()  and srand() in the Linux C Library use the same random number generator as random() and
       srandom(), so the lower-order bits should be as random as the higher-order bits.  However, on older rand()  imple-
       mentations,  and  on  current implementations on different systems, the lower-order bits are much less random than
       the higher-order bits.  Do not use this function in applications intended to be portable when good  randomness  is

       In  Numerical  Recipes in C: The Art of Scientific Computing (William H. Press, Brian P. Flannery, Saul A. Teukol-
       sky, William T. Vetterling; New York: Cambridge University Press, 1992 (2nd ed., p. 277)), the following  comments
       are made:
              "If  you  want  to  generate a random integer between 1 and 10, you should always do it by using high-order
              bits, as in

                     j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

              and never by anything resembling

                     j = 1 + (rand() % 10);

              (which uses lower-order bits)."

       Random-number generation is a complex topic.  The Numerical Recipes in C book (see reference  above)  provides  an
       excellent discussion of practical random-number generation issues in Chapter 7 (Random Numbers).

       For  a  more theoretical discussion which also covers many practical issues in depth, please see Chapter 3 (Random
       Numbers) in Donald E. Knuth's The Art of Computer Programming, volume 2 (Seminumerical Algorithms), 2nd ed.; Read-
       ing, Massachusetts: Addison-Wesley Publishing Company, 1981.

       The functions rand() and srand() conform to SVID 3, 4.3BSD, ISO 9899, POSIX 1003.1-2003.  The function rand_r() is
       from POSIX 1003.1-2003.

       drand48(3), random(3)

                                                        2003-11-15                                                RAND(3)
If your looking for a better randomness then that, check out drand48 (man drand48) which is also in the cstdlib include file.

Last edited by jtshaw; 11-07-2005 at 11:18 AM.
Old 11-07-2005, 06:58 PM   #3
Senior Member
Registered: Aug 2005
Posts: 1,755

Rep: Reputation: 50
#include <cstdlib>

int foo = rand() ;
Old 11-07-2005, 08:59 PM   #4
Registered: Jun 2005
Posts: 542

Rep: Reputation: 34
You need to seed it. The subject is sufficiently explained in the web. The same seed will generate the same sequence of pseudo-random numbers. Usually, it's seeded with the time() function, but running the program at the same time (less than one second) will get you the same sequence, so it's better to use gettimeofday() if available, multiplying seconds and microseconds.
Old 11-08-2005, 11:15 AM   #5
Registered: Dec 2004
Location: Vietnam (Việt Nam)
Distribution: Gentoo (desktop), Arch linux (laptop)
Posts: 728

Original Poster
Rep: Reputation: 33
Would you mind give me an examples please?
1 members found this post helpful.
Old 11-09-2005, 01:01 AM   #6
Registered: Jun 2005
Posts: 542

Rep: Reputation: 34
void seedit(void)
    struct timeval tv;

    gettimeofday(&tv, NULL);

    srand(tv.tv_sec * tv.tv_usec);
You may use either srand() or srandom(). To get pseudo-random numbers use either rand() or random() and apply the % operator an any arithmetic expression to make it suitable in the range you need
1 members found this post helpful.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
can bash generate random digit? sorno Linux - Newbie 5 08-17-2005 07:05 AM
Random number generators blufire Programming 5 11-09-2004 07:02 PM
generate a big number of folders mannoulla Linux - Software 1 06-14-2004 05:27 PM
Python problems trying to generate a random number davholla Programming 0 10-27-2003 05:07 AM
I need random number in C ... purpleburple Programming 4 10-28-2002 05:37 AM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:03 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration