Understanding Random Numbers and Simulations in C++, Study notes of Computer Science

How to generate random numbers in c++ using the rand() function and how to use them in simulations. It also covers the concept of pseudorandom numbers and the use of seeds to ensure different results in each program run. A simple example of simulating die tosses is provided.

Typology: Study notes

2020/2021

Uploaded on 04/10/2021

maxbrian
maxbrian 🇫🇯

1 document

1 / 2

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
168 Chapter 4 Loops
38. Why is there a statement
cout << endl
in the outer loop but not in the inner loop?
39. How would you change the program so that all powers from x0 to x5 are
displayed?
40. If you make the change in Self Check 39, how many values are displayed?
41. What do the following nested loops display?
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
cout << i + j;
}
cout << endl;
}
42. Write nested loops that make the following pattern of brackets:
[][][][]
[][][][]
[][][][]
Practice It Now you can try these exercises at the end of the chapter: R4.23, P4.21, P4.22.
4.9 Random Numbers and Simulations
A simulation program uses the computer to simulate an activity in the real world (or
an imaginary one). Simulations are commonly used for predicting climate change,
analyzing traffic, picking stocks, and many other applications in science and busi-
ness. In the following sections, you will learn how to imple ment simulations that
model phenomena with a degree of randomness.
4.9.1 Generating Random Numbers
Many events in the real world are difficult to predict with absolute precision, yet we
can sometimes know the average behavior quite well. For example, a store may know
from experience that a customer arrives every five minutes. Of course, that is an aver-
age—customers don’t arrive in five minute intervals. To accurately model customer
traffic, you want to take that random fluctuation into account. Now, how can you
run such a simulation in the computer?
The C++ library has a random number generator, which produces numbers that
appear to be com pletely random. Calling
rand()
yields a random integer between
0 and
RAND_MAX
(which is an implementa tion-dependent constant, typically, but not
always, the largest valid
int
value). Call
rand()
again, and you get a different number.
The
rand
function is declared in the
<cstdlib>
header.
The following program calls the
rand
function ten times.
ch04/random.cpp
1
#include <iostream>
2
#include <cstdlib>
3
4
using namespace std;
SELF CHECK
In a simulation, you
use the computer to
simulate an activity.
You can introduce
randomness by
calling the random
number generator.
cfe2_ch04_p131_192.indd 168 10/28/10 8:13 PM
pf2

Partial preview of the text

Download Understanding Random Numbers and Simulations in C++ and more Study notes Computer Science in PDF only on Docsity!

168 Chapter 4 Loops

38. Why is there a statement cout << endl in the outer loop but not in the inner loop? 39. How would you change the program so that all powers from x^0 to x^5 are displayed? 40. If you make the change in Self Check 39, how many values are displayed? 41. What do the following nested loops display? for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { cout << i + j; } cout << endl; } 42. Write nested loops that make the following pattern of brackets: [][][][] [][][][] [][][][]

Practice It Now you can try these exercises at the end of the chapter: R4.23, P4.21, P4.22.

4.9 Random Numbers and Simulations

A simulation program uses the computer to simulate an activity in the real world (or an imaginary one). Simulations are commonly used for predicting climate change, analyzing traffic, picking stocks, and many other applications in science and busi- ness. In the following sections, you will learn how to implement simulations that model phenomena with a degree of randomness.

4.9.1 Generating Random Numbers

Many events in the real world are difficult to predict with absolute precision, yet we can sometimes know the average behavior quite well. For example, a store may know from experience that a customer arrives every five minutes. Of course, that is an aver- age—customers don’t arrive in five minute intervals. To accurately model customer traffic, you want to take that random fluctuation into account. Now, how can you run such a simulation in the computer? The C++ library has a random number generator , which produces numbers that appear to be completely random. Calling rand() yields a random integer between 0 and RAND_MAX (which is an implementa tion-dependent constant, typically, but not always, the largest valid int value). Call rand() again, and you get a different number. The rand function is declared in the header. The following program calls the rand function ten times.

ch04/random.cpp

1 #include

2 #include

4 using namespace std;

S E L F C H E C K

In a simulation, you use the computer to simulate an activity. You can introduce randomness by calling the random number generator.

4.9 Random Numbers and Simulations 169

6 int main()

8 for (int i = 1; i <= 10; i++)

10 int r = rand();

11 cout << r << endl;

13 return 0;

Program Run

Actually, the numbers are not completely random. They are drawn from sequences

of numbers that don’t repeat for a long time. These sequences are actually computed

from fairly simple formulas; they just behave like random numbers. For that reason,

they are often called pseudorandom numbers.

Try running the program again. You will get the exact same output! This confirms

that the random numbers are generated by formulas. However, when running simu-

lations, you don’t always want to get the same results. To overcome this problem,

specify a seed for the random number sequence. Every time you use a new seed, the

random number generator starts generating a new sequence. The seed is set with the

srand function. A simple value to use as a seed is the current time:

srand(time(0));

Simply make this call once in your program, before generating any random numbers.

Then the random numbers will be different in every program run. Also include the

header that declares the time function.

4.9.2 Simulating Die Tosses

In actual applications, you need to transform the output from

the random number generator into different ranges. For exam-

ple, to simulate the throw of a die, you need random numbers

between 1 and 6.

Here is the general recipe for computing random integers

between two bounds a and b. As you know from Program-

ming Tip 4.3 on page 147, there are b - a + 1 values between a

and b, including the bounds themselves. First compute

rand() % (b - a + 1) to obtain a random value between 0 and

b - a, then add a, yielding a random value between a and b:

int r = rand() % (b - a + 1) + a;