티스토리 뷰
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:
#include <cstdlib> #include <iostream> using namespace std; int main() { int random_integer = rand(); cout << random_integer << endl; }
#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.
#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:
#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; } }
#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: Sep 2003
Location: deep withing 100100010100
Posts: 206
Reputation:
Rep Power: 6
Solved Threads: 1
I hate to be forced to pm you so many times Bob but In my internet explorer browser the font of your webpage is as small as ants and I don't know how to make them look bigger.
About this tutorial , I would like to know what is the " actual " use of random number generating.
About this tutorial , I would like to know what is the " actual " use of random number generating.
Forum bully
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:
Rep Power: 0
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;
}
}
'Language > C' 카테고리의 다른 글
2 차원 벡터 사용함수 및 여러가지 기법 (0) | 2009.03.31 |
---|---|
vector class/template이용한 2차원 배열 생성 (0) | 2009.02.04 |
이차원 동적 배열 설정 (0) | 2009.01.04 |
VS2005 에서 VS2008 로 넘어갈때의 팁 (0) | 2008.09.01 |
Financial Numerical Recipes in C ++. (0) | 2008.08.12 |
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Linear Gaussian Model
- 금융수학
- 어렵다크레딧
- Fallback rate
- 크레딧투자
- JPY
- LG
- 포트폴리오
- computational finance
- 꿀떡이
- mathematical finance
- Risk Free Rate
- 와인
- market convention
- recession
- 리보중단
- RfR
- CHF
- 회고2023
- 금융공학
- 유동성최악
- XAG
- financial
- 가을
- SOFR
- finance
- Volatility Ratio
- random gereragtor
- VBA
- 세식구
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함