| | |
C++ Random Numbers
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Feb 2003
Posts: 129
Reputation:
Solved Threads: 1
Intro
This tutorial provides a brief introduction to the random number functions that come as part of the C++ standard library, namely rand() and srand().
rand() and RAND_MAX
The C++ standard library includes a pseudo random number generator for generating random numbers. In order to use it we need to include the <cstdlib> header. To generate a random number we use the rand() function. This will produce a result in the range 0 to RAND_MAX, where RAND_MAX is a constant defined by the implementation.
Here's a piece of code that will generate a single random number:
The value of RAND_MAX varies between compilers and can be as low as 32767, which would give a range from 0 to 32767 for rand(). To find out the value of RAND_MAX for your compiler run the following small piece of code:
srand()
The pseudo random number generator produces a sequence of numbers that gives the appearance of being random, when in fact the sequence will eventually repeat and is predictable.
We can seed the generator with the srand() function. This will start the generator from a point in the sequence that is dependent on the value we pass as an argument. If we seed the generator once with a variable value, for instance the system time, before our first call of rand() we can generate numbers that are random enough for simple use (though not for serious statistical purposes).
In our earlier example the program would have generated the same number each time we ran it because the generator would have been seeded with the same default value each time. The following code will seed the generator with the system time then output a single random number, which should be different each time we run the program.
Don't make the mistake of calling srand() every time you generate a random number; we only usually need to call srand() once, prior to the first call to rand().
Generating a number in a specific range
If we want to produce numbers in a specific range, rather than between 0 and RAND_MAX, we can use the modulo operator. It's not the best way to generate a range but it's the simplest. If we use rand()%n we generate a number from 0 to n-1. By adding an offset to the result we can produce a range that is not zero based. The following code will produce 20 random numbers from 1 to 10:
A better method, though slightly more complicated, is given below. This overcomes problems that are sometimes experienced with some types of pseudo random number generator that might be supplied with your compiler. As before, this will output 20 random numbers from 1 to 10.
Conclusion
If you need to use a pseudo random number generator for anything even remotely serious you should avoid the simple generator that comes with your compiler and use something more sophisticated instead. That said, rand() still has its place and you may find it useful.
This tutorial provides a brief introduction to the random number functions that come as part of the C++ standard library, namely rand() and srand().
rand() and RAND_MAX
The C++ standard library includes a pseudo random number generator for generating random numbers. In order to use it we need to include the <cstdlib> header. To generate a random number we use the rand() function. This will produce a result in the range 0 to RAND_MAX, where RAND_MAX is a constant defined by the implementation.
Here's a piece of code that will generate a single random number:
C++ Syntax (Toggle Plain Text)
#include <cstdlib> #include <iostream> using namespace std; int main() { int random_integer = rand(); cout << random_integer << endl; }
C++ Syntax (Toggle Plain Text)
#include <cstdlib> #include <iostream> using namespace std; int main() { cout << "The value of RAND_MAX is " << RAND_MAX << endl; }
The pseudo random number generator produces a sequence of numbers that gives the appearance of being random, when in fact the sequence will eventually repeat and is predictable.
We can seed the generator with the srand() function. This will start the generator from a point in the sequence that is dependent on the value we pass as an argument. If we seed the generator once with a variable value, for instance the system time, before our first call of rand() we can generate numbers that are random enough for simple use (though not for serious statistical purposes).
In our earlier example the program would have generated the same number each time we ran it because the generator would have been seeded with the same default value each time. The following code will seed the generator with the system time then output a single random number, which should be different each time we run the program.
C++ Syntax (Toggle Plain Text)
#include <cstdlib> #include <ctime> #include <iostream> using namespace std; int main() { srand((unsigned)time(0)); int random_integer = rand(); cout << random_integer << endl; }
Generating a number in a specific range
If we want to produce numbers in a specific range, rather than between 0 and RAND_MAX, we can use the modulo operator. It's not the best way to generate a range but it's the simplest. If we use rand()%n we generate a number from 0 to n-1. By adding an offset to the result we can produce a range that is not zero based. The following code will produce 20 random numbers from 1 to 10:
C++ Syntax (Toggle Plain Text)
#include <cstdlib> #include <ctime> #include <iostream> using namespace std; int main() { srand((unsigned)time(0)); int random_integer; for(int index=0; index<20; index++){ random_integer = (rand()%10)+1; cout << random_integer << endl; } }
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { srand((unsigned)time(0)); int random_integer; int lowest=1, highest=10; int range=(highest-lowest)+1; for(int index=0; index<20; index++){ random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0)); cout << random_integer << endl; } }
Conclusion
If you need to use a pseudo random number generator for anything even remotely serious you should avoid the simple generator that comes with your compiler and use something more sophisticated instead. That said, rand() still has its place and you may find it useful.
Last edited by happygeek; Nov 12th, 2006 at 11:47 am. Reason: Formatting
•
•
Join Date: Feb 2003
Posts: 129
Reputation:
Solved Threads: 1
Thanks for the feedback about the font size on my web site. I wasn't aware that anyone had a problem with it till now. I'll look into it. Perhaps you could let me know what your screen resolution is set to, or anything else that you feel might be relevant. Is the font too small on all of the pages? Time is short right now but in the near future I'll try to come up with a generic solution. In the meantime, the content is available as a PDF download from the site, or can be sent out via email.
As for the use of generating random numbers, well almost any use really. For example, someone might simulate rolling a dice in their program, generating numbers in the range 1 to 6, or have an array of character strings and generate them seemingly at random by generating a random number within the range of valid indexes for the array. A lottery program might generate numbers using rand(). Almost anything you can think of, but remember that the random number generators that ship with compilers are usually pretty basic and not adequate for serious applications, e.g. scientific or crypto use. Better generators are available.
As for the use of generating random numbers, well almost any use really. For example, someone might simulate rolling a dice in their program, generating numbers in the range 1 to 6, or have an array of character strings and generate them seemingly at random by generating a random number within the range of valid indexes for the array. A lottery program might generate numbers using rand(). Almost anything you can think of, but remember that the random number generators that ship with compilers are usually pretty basic and not adequate for serious applications, e.g. scientific or crypto use. Better generators are available.
•
•
Join Date: Apr 2004
Posts: 1
Reputation:
Solved Threads: 0
•
•
•
•
Originally Posted by Bob
This tutorial provides a brief introduction to the random number functions that come as part of the C++ standard library, namely rand() and srand().
rand() and RAND_MAX
The C++ standard library includes a pseudo random number generator for generating random numbers. In order to use it we need to include the <cstdlib> header. To generate a random number we use the rand() function. This will produce a result in the range 0 to RAND_MAX, where RAND_MAX is a constant defined by the implementation.
Here's a piece of code that will generate a single random number:
#include <cstdlib>The value of RAND_MAX varies between compilers and can be as low as 32767, which would give a range from 0 to 32767 for rand(). To find out the value of RAND_MAX for your compiler run the following small piece of code:
#include <iostream>
using namespace std;
int main()
{
int random_integer = rand();
cout << random_integer << endl;
}
#include <cstdlib>srand()
#include <iostream>
using namespace std;
int main()
{
cout << "The value of RAND_MAX is " << RAND_MAX << endl;
}
The pseudo random number generator produces a sequence of numbers that gives the appearance of being random, when in fact the sequence will eventually repeat and is predictable.
We can seed the generator with the srand() function. This will start the generator from a point in the sequence that is dependent on the value we pass as an argument. If we seed the generator once with a variable value, for instance the system time, before our first call of rand() we can generate numbers that are random enough for simple use (though not for serious statistical purposes).
In our earlier example the program would have generated the same number each time we ran it because the generator would have been seeded with the same default value each time. The following code will seed the generator with the system time then output a single random number, which should be different each time we run the program.
#include <cstdlib>Don't make the mistake of calling srand() every time you generate a random number; we only usually need to call srand() once, prior to the first call to rand().
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer = rand();
cout << random_integer << endl;
}
Generating a number in a specific range
If we want to produce numbers in a specific range, rather than between 0 and RAND_MAX, we can use the modulo operator. It's not the best way to generate a range but it's the simplest. If we use rand()%n we generate a number from 0 to n-1. By adding an offset to the result we can produce a range that is not zero based. The following code will produce 20 random numbers from 1 to 10:
#include <cstdlib>A better method, though slightly more complicated, is given below. This overcomes problems that are sometimes experienced with some types of pseudo random number generator that might be supplied with your compiler. As before, this will output 20 random numbers from 1 to 10.
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
for(int index=0; index<20; index++){
random_integer = (rand()%10)+1;
cout << random_integer << endl;
}
}
#include <iostream>If you need to use a pseudo random number generator for anything even remotely serious you should avoid the simple generator that comes with your compiler and use something more sophisticated instead. That said, rand() still has its place and you may find it useful.
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest=1, highest=10;
int range=(highest-lowest)+1;
for(int index=0; index<20; index++){
random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0));
cout << random_integer << endl;
}
}
my question is, for the functions on choosing random numbers in a specific range, what should i do to make the cout one by one?
As in, like the function given above, it gives the whole 20 outputs at once, but what i would like to do is to get the output one by one, how could i do that?
and let's say i have a range from 2 to N, what should i do to get the output only from 2 to N and not 0 to N?because what's given in the previous thread is a function to choose from 0 to N.
thank you
•
•
Join Date: Oct 2004
Posts: 2
Reputation:
Solved Threads: 0
Hi BOb,
Thanks for the random number generator programs.
I want to experiment with true random number generator and need a program that runs by a input through the keyboard or soundcard. that is a word or a noise - a wave file. I must get the numbers from 00 to 99 each one from every decade. e.g, oo,13,24,37,49,52,65,73,88,91;
Please send me your tutorial on this through my e-mail also.
Thanks and best regards, Bob,
Jyeshta
Thanks for the random number generator programs.
I want to experiment with true random number generator and need a program that runs by a input through the keyboard or soundcard. that is a word or a noise - a wave file. I must get the numbers from 00 to 99 each one from every decade. e.g, oo,13,24,37,49,52,65,73,88,91;
Please send me your tutorial on this through my e-mail also.
Thanks and best regards, Bob,
Jyeshta
•
•
Join Date: Oct 2004
Posts: 2
Reputation:
Solved Threads: 0
Hi Bob,
Good day,
I tried to execute the program[last one] you presented there in the random number generator file. I have TURBOC 30 which is C++ compiler and says that it don't have i0stream, and the other two header files, Will you please send them to me? I tried to install Boreland C++ but it is not showing the compiler . When I click on the icon it just appears and dissappears. I have windows XP and don't know how to solve these problems. Your help is highly appreciated,
Thanks and best regards, BOb,
Jyeshta
Good day,
I tried to execute the program[last one] you presented there in the random number generator file. I have TURBOC 30 which is C++ compiler and says that it don't have i0stream, and the other two header files, Will you please send them to me? I tried to install Boreland C++ but it is not showing the compiler . When I click on the icon it just appears and dissappears. I have windows XP and don't know how to solve these problems. Your help is highly appreciated,
Thanks and best regards, BOb,
Jyeshta
•
•
Join Date: Dec 2004
Posts: 1
Reputation:
Solved Threads: 0
Hey,
Ive been playing around with your random number generator and I have a couple questions, first I was wondering how can i make it where numbers can't repeat themselves, to put every number in once. The second question is, is there any code that you can put in names nd generate them in random order.
Thanks
Ive been playing around with your random number generator and I have a couple questions, first I was wondering how can i make it where numbers can't repeat themselves, to put every number in once. The second question is, is there any code that you can put in names nd generate them in random order.
Thanks
•
•
•
•
how can i make it where numbers can't repeat themselves
•
•
•
•
is there any code that you can put in names nd generate them in random order
"Bill"
"Bob"
"James"
"Chris"
"Thomas"
so you would generate numbers from 0 to 4 and might get:
3
1
4
0
2
in a separate array. Then copy across from the string array the string at the index specified by the second array. Then it becomes:
"Chris"
"Bob"
"Thomas"
"Bill"
"James"
Hope this helps
http://sales.carina-e.com
no www
no nonsense
coming soon to a pc near you! :cool:
no www
no nonsense
coming soon to a pc near you! :cool:
•
•
•
•
Originally Posted by aylina
my question is, for the functions on choosing random numbers in a specific range, what should i do to make the cout one by one?
As in, like the function given above, it gives the whole 20 outputs at once, but what i would like to do is to get the output one by one, how could i do that?
thank you![]()
for example:
C++ Syntax (Toggle Plain Text)
#include <iostream> #include <conio> #include <ctime> #include <cstdlib> using namespace std; int main() { srand((unsigned)time(0)); int random_integer; int lowest=1, highest=10; int range=(highest-lowest)+1; for(int index=0; index<20; index++){ random_integer = lowest+int(range*rand()/(RAND_MAX + 1.0)); cout << random_integer << endl; getch(); } }
•
•
•
•
Originally Posted by jyeshta
Hi Bob,
Good day,
I tried to execute the program[last one] you presented there in the random number generator file. I have TURBOC 30 which is C++ compiler and says that it don't have i0stream, and the other two header files, Will you please send them to me? I tried to install Boreland C++ but it is not showing the compiler . When I click on the icon it just appears and dissappears. I have windows XP and don't know how to solve these problems. Your help is highly appreciated,
Thanks and best regards, BOb,
Jyeshta
![]() |
Similar Threads
- Compile time errors in C++ while generating random numbers (C++)
- C++ Reorder random numbers (C++)
- random numbers all different??? (C++)
Other Threads in the C++ Forum
- Previous Thread: File read problem
- Next Thread: passing linked lists through functions??
| Thread Tools | Search this Thread |
api array based binary c++ c/c++ calculator char char* class classes code coding compile console conversion count database delete deploy desktop developer directshow dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp iamthwee ifstream input int integer java lib linkedlist linker linux list loop looping loops map math matrix memory multiple news number numbertoword output parameter pointer problem program programming project python random read recursion recursive reference return rpg sorting string strings struct temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock wordfrequency wxwidgets




