0% found this document useful (0 votes)
12 views

Simulation and Modeling- Lecture 2

Uploaded by

tempire.hky971
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Simulation and Modeling- Lecture 2

Uploaded by

tempire.hky971
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

SIMULATION AND MODELING-LECTURE 2

Random Number

The ability to generate random numbers can be useful in certain kinds of


programs, particularly in games, statistical modelling programs, and
cryptographic applications that need to encrypt and decrypt things. Take
games for example -- without random events, monsters would always attack
you the same way, you’d always find the same treasure, the dungeon layout
would never change, etc… and that would not make for a very good game.

In real life, we often produce randomization by doing things like flipping a


coin, rolling a dice, or shuffling a deck of cards. These events aren’t actually
random, but involve so many physical variables (e.g. gravity, friction, air
resistance, momentum, etc…) that they become almost impossible to predict
or control, and (unless you’re a magician) produce results that are for all
intents and purposes random.

However, computers aren’t designed to take advantage of physical variables


-- your computer can’t toss a coin, throw a dice, or shuffle real cards. Modern
computers live in a controlled electrical world where everything is binary (0
or 1) and there is no in-between. By their very nature, computers are
designed to produce results that are as predictable as possible. When you
tell the computer to calculate 2 + 2, you always want the answer to be 4.
Not 3 or 5 on occasion.
Consequently, computers are generally incapable of generating truly random
numbers (at least through software). Instead, modern programs
typically simulate randomness using an algorithm.

The use of Random numbers lies at the foundation of modelling and


simulations. Computer applications such as simulations, games, graphics,
etc., often need the ability to generate random numbers for such application.
The quality of a random number generator is proportional to its period, or
the number of random numbers it can produce before a repeating pattern
sets in. In large-scale simulations, different algorithms (called shift-register
and lagged-Fibonacci) can be used, although these also have some
drawbacks, combining two different types of generators may produce the
best results.
Definition
Random Number can be defined as numbers that show no consistent
pattern, with each number in a series and are neither affected in any way by
the preceding number, nor predictable from it. One way to get random digits
is to simply start with an arbitrary number with a specified number of digits,
for example 4 digits. The first number is called the seed. The seed is
multiplied by a constant number of the same number of digits(length), and
the desired number of digits is taken off the right end of the product. The
result becomes the new seed. It is again multiplied by the original constant
to generate a new product, and the process is repeated as often as desired.
The result is a series of digits that appear randomly distributed as though
generated by throwing a die or spinning a wheel. This type of algorithm is
called a congruential generator.
A Congruential Generator is a type of pseudorandom number generator
(PRNG) that uses a recursive formula to generate a sequence of numbers.
Here's an explanation with an example:

The LCG uses the following recursive formula:

X(n+1) = (a * X(n) + c) mod m

Where:

- X(n) is the current random number


- X(n+1) is the next random number
- a is the multiplier
- c is the increment
- m is the modulus

Example:

Let's use the following parameters:

- a = 1103515245
- c = 12345
- m = 2^31
- Initial seed (X(0)) = 123456789

Using the LCG formula, we can generate a sequence of random numbers:

X(1) = (1103515245 * 123456789 + 12345) mod 2^31 = 987654321


X(2) = (1103515245 * 987654321 + 12345) mod 2^31 = 456789012
X(3) = (1103515245 * 456789012 + 12345) mod 2^31 = 210987654

And so on...

Properties of Congruential Generators:

1. Periodicity: LCGs have a periodic output, meaning that the sequence will
eventually repeat.
2. Uniform distribution: LCGs can produce uniformly distributed random
numbers, but this depends on the choice of parameters.
3. Determinism: LCGs are deterministic, meaning that given the same initial
seed and parameters, the same sequence of numbers will be generated.

Advantages and Disadvantages:

Advantages:

1. Fast and efficient: LCGs are relatively fast and efficient compared to other
PRNGs.
2. Easy to implement: LCGs are simple to implement, requiring only basic
arithmetic operations.

Disadvantages:

1. Limited randomness: LCGs can produce predictable and non-random


output, especially with poor parameter choices.
2. Periodicity: LCGs have a limited period, which can be a problem in
applications requiring very long sequences of random numbers.

Pseudorandom Number Generation

In this section we look at how random numbers may be generated by human


beings for use in simulating a system or by computer for use while
simulating an event.

What we usually do is to take for instance ten pieces of papers and number
them 0,1,2,3,4,5,6,7,8, and 9 , fold and place them in a box. Shake the box
and thoroughly mix the slips of paper. Select a slip; then record the number
that is on it. Replace the slip and repeat this procedure over and over. The
resultant record of digits is a realized sequence of random numbers.
Assuming you thoroughly mix the slips before every draw, the nth digit of the
sequence has an equal or uniform chance of being any of the digits 0, 1,
2,3,4,5,6,7,8, 9 irrespective of all the preceding digits in the recorded
sequence.

In some simulations, we use random numbers that are between 0 and 1. For
example, if you need such numbers with four decimal digits, then you can
take four at a time from the recorded sequence of random digits, and place a
decimal point in front of each group of four.

To illustrate, if the sequence of digits is 358083429261… then the four


decimal placed random numbers are .3580, .8342, and .9261.
Most programming languages provide PRNGs:
import random
random.seed(42) # Set seed
print(random.randint(1, 100)) # Generate pseudo-random number

Random Numbers in Computer


How does computer generate a sequence of random numbers?
One way is to perform the above ―slip-in-a-box‖ experiment and then store
the recorded sequence in a computer-backing store.

Experts in computer science have devised mathematical processes for


generating digits that yield sequences satisfying many of the statistical
properties of a truly random process. To illustrate, if you examine a long
sequence of digits produced by deterministic formulas, each digit will occur
with nearly the same frequency, odd numbers will be followed by even
numbers about as often as by odd numbers, different pairs of numbers occur
with nearly the same frequency, etc. Since such a process is not really
random, it is called pseudo-random number generator.

The other ways of generating pseudo-random numbers are:


1. Computer simulation languages and indeed some programming
languages such as BASIC have built-in pseudo-random number
generators. In computer simulation situations where this facility is not
available in the language you are using, you will have to write you own
pseudo-random number generator (see how to do this later).
2. The results of experiments such as the one previously describe above
are published in books of statistical tables. In hand simulation, it may
be appropriate to use a published table of random numbers.
3. The conventional six-sided unbiased die may also be used to generate
a sequence of random digits in the set (1, 2, 3, 4, 5, 6) where each
digit has a probability 1/6 of occurrence.

Exercise
Suggest one or two experimental set-ups (analogous to the slip-in-a-box
approach) for generating uniform random digits.

Using the RND Function in BASIC


The BASIC programming language has a numeric function named RND,
which generates random numbers between 0 and 1. Each time RND is
executed, a pseudo random number between 0 and 1 is generated. Using
RND function at any time will always generate the
same sequence of pseudo random numbers unless we vary the random
number seed using the BASIC statement:

RANDOMIZE

This way, we can control the sequence of random numbers generated.


RANDOMIZE will result to the following prompt on the VDU:

Random Number Seed (-32768 to 32767)?

Suppose your response to the above prompt is 100. Then the computer
would use this number, 100, to generate the first random number. This
number generated is used to generate the next random number. Thus by
specifying the seed for the first random number, we are in a way controlling
all random numbers that will be generated until the seed is reset. A control
such as this can be very useful in validating a simulation program or other
computer programs that use random numbers. Consider the following BASIC
program:
FOR K% = 1 TO 5
PRINT RND NEXT K%
END

If the above program is run, some seven-digit decimal numbers like the
following will be displayed:
.6291626, .1948297, .6305799, .8625749, .736353. The particular
digits displayed depend on the system time.

Every time you run the above program, different sequence of numbers will
be displayed. Now add a RANDOMIZE statement to the program:

RANDOMIZE TIMER FOR K% = 1 TO 5


PRINT RND NEXT K%
END

If you run this program with 300 as a response to the prompt for the random
number seed, the following may be displayed:
.1851404, .9877729, .806621, .8573399, .6208935

Exercise
Find out whether the same set of random numbers will be displayed each
time the above program is run with seed 300.
Example 1
A simple python program that will stimulate the tossing of two dice and
display the value obtained after each toss, and the total value of the dice is
shown below.
import random

def roll_dice():
# Simulate rolling two dice
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)

# Calculate the total value


total = die1 + die2

# Display the results


print(f"Die 1: {die1}")
print(f"Die 2: {die2}")
print(f"Total: {total}")

# Run the dice roll simulation


roll_dice()
How It Works:
random.randint(1, 6) generates a random integer between 1 and 6 for each
die.
The program adds the values of the two dice to compute the total.
The values of each die and the total are printed to the console.
Example Output:
If you run the program, you might see:
Die 1: 4
Die 2: 5
Total: 9

Exercise
Run the program of example 1 several times using different random number
seeds to determine if the integers generated for the individual die are
uniformly distributed between 1 and 6 inclusive.

Example 2

Another python program to simulate the tossing of a fair coin 10 times. The
program displays a H when a head appears and a T when a tail appears.

import random

def toss_coin():
# Simulate 10 coin tosses
results = []
for _ in range(10):
toss = "H" if random.randint(0, 1) == 0 else "T"
results.append(toss)

# Display the results


print("Coin Toss Results:", " ".join(results))

# Run the coin toss simulation


toss_coin()

How It Works:
random.randint(0, 1): Generates either 0 or 1 randomly.
0 is interpreted as "H" (heads).
1 is interpreted as "T" (tails).
Loop: Simulates 10 tosses.
Results Display: The results are stored in a list and printed as a space-
separated string.
Example Output:
Running the program might produce something like this:
Copy code
Coin Toss Results: H T H H T T H T T H
Example 3
Suppose the output of the program of example 3 is: HHTHHTTTHH and that
there are two players X and Y involved in the tossing of the coin. Given that
player X wins N50.00 from player Y if a head appears and loses it to player
Y if a tail appears. Determine who won the game and by how much.

Solution
From the output there are 6 heads and 4 tails.
Player X wins N50.00 x 6 = N300.00 from player Y. He loses N50.00 x 4 =
N200.00 to player Y.
Thus, player X won the game with N300.00 – N200.00 = N100.00.
Explanation of Example 3
This scenario involves a coin-toss game with two players, X and Y, and a
simple betting rule:
If a head (H) appears: Player X wins N50.00 from Player Y.
If a tail (T) appears: Player X loses N50.00 to Player Y.

Steps to Solve the Problem


Count Heads (H) and Tails (T):
From the coin toss output: HHTHHTTTHH, there are:
6 heads (H)
4 tails (T)
Calculate Winnings and Losses for Player X:
Player X wins N50.00 for each head:
Winnings from heads=6×50=N300.00Winnings from heads=6×50=N300.00
Player X loses N50.00 for each tail:
Losses from tails=4×50=N200.00Losses from tails=4×50=N200.00
Determine the Net Outcome for Player X:
Player X's net gain (or winnings) is calculated as:
Net winnings=Winnings from heads−Losses from tailsNet winnings=Winning
s from heads−Losses from tailsSubstituting the
values:Net winnings=300−200=N100.00Net winnings=300−200=N100.00
Result:
Player X won the game with N100.00.

Key Takeaways:
The problem is straightforward arithmetic: count occurrences of heads and
tails, calculate the corresponding monetary transactions, and compute the
net result.
The approach applies to any output of coin tosses—just count heads and
tails, and repeat the calculations based on the given rules.

Properties of a Good Random Number Generator


The random numbers generated should;
a. have as nearly as possible a uniform distribution.
b. should be fast
c. not require large amounts of memory.
d. have a long period.
e. be able to generate a different set of random numbers or a series of
numbers.
f. not degenerate.

ASSIGNMENT
Write a python program to generate thirty random integer numbers
distributed between 20 and 50. Your program should ensure that no number
is repeated.
2.Write a Python program using the quadratic congruential method to
generate 15 random integer numbers between 1 and 50.
def quadratic_congruential_method(seed, a, b, c, m, n):
"""
Generates random numbers using the Quadratic Congruential Method.

Args:
seed (int): Initial seed value.
a (int): Multiplier constant.
b (int): Linear constant.
c (int): Additive constant.
m (int): Modulus.
n (int): Number of random numbers to generate.

Returns:
list: List of generated random integers.
"""
random_numbers = []
x = seed # Initialize with the seed value

for _ in range(n):
x = (a * (x**2) + b * x + c) % m # Quadratic congruential formula
random_numbers.append(x if x > 0 else 1) # Ensure range starts from
1

return random_numbers

# Parameters for the quadratic congruential method


seed = 17 # Initial seed
a=7 # Multiplier constant
b=5 # Linear constant
c=3 # Additive constant
m = 51 # Modulus (max value + 1)
n = 15 # Number of random numbers to generate

# Generate and display the random numbers


random_numbers = quadratic_congruential_method(seed, a, b, c, m, n)
print("Generated Random Numbers (1 to 50):", random_numbers)

Generated Random Numbers (1 to 50): [17, 22, 29, 40, 19, 14, 43, 8, 1, 28,
50, 48, 36, 23, 42]
Verification & Validation

One of the real problems that the simulation analyst faces is to validate the
model. The simulation model is valid only if the model is an accurate
representation of the actual system, else it is invalid.

Validation and verification are the two steps in any simulation project to
validate a model.

 Validation is the process of comparing two results. In this process, we


need to compare the representation of a conceptual model to the real
system. If the comparison is true, then it is valid, else invalid.
 Verification is the process of comparing two or more results to ensure
its accuracy. In this process, we have to compare the model’s
implementation and its associated data with the developer's
conceptual description and specifications.

Verification & Validation Techniques

There are various techniques used to perform Verification & Validation of


Simulation Model. Following are some of the common techniques −

Techniques to Perform Verification of Simulation Model

Following are the ways to perform verification of simulation model −

 By using programming skills to write and debug the program in sub-


programs.
 By using “Structured Walk-through” policy in which more than one
person is to read the program.
 By tracing the intermediate results and comparing them with observed
outcomes.
 By checking the simulation model output using various input
combinations.
 By comparing final simulation result with analytic results.

Techniques to Perform Validation of Simulation Model

Step 1 − Design a model with high validity. This can be achieved using the
following steps −
 The model must be discussed with the system experts while designing.
 The model must interact with the client throughout the process.
 The output must supervised by system experts.
Step 2 − Test the model at assumptions data. This can be achieved by
applying the assumption data into the model and testing it quantitatively.
Sensitive analysis can also be performed to observe the effect of change in
the result when significant changes are made in the input data.
Step 3 − Determine the representative output of the Simulation model. This
can be achieved using the following steps −
 Determine how close is the simulation output with the real system
output.
 Comparison can be performed using the Turing Test. It presents the
data in the system format, which can be explained by experts only.
 Statistical method can be used for compare the model output with the
real system output.
Model Data Comparison with Real Data

After model development, we have to perform comparison of its output data


with real system data. Following are the two approaches to perform this
comparison.

Validating the Existing System

In this approach, we use real-world inputs of the model to compare its output
with that of the real-world inputs of the real system. This process of
validation is straightforward, however, it may present some difficulties when
carried out, such as if the output is to be compared to average length,
waiting time, idle time, etc. it can be compared using statistical tests and
hypothesis testing. Some of the statistical tests are chi-square test,
Kolmogorov-Smirnov test, Cramer-von Mises test, and the Moments test.

Validating the First Time Model

Consider we have to describe a proposed system which doesn’t exist at the


present nor has existed in the past. Therefore, there is no historical data
available to compare its performance with. Hence, we have to use a
hypothetical system based on assumptions. Following useful pointers will
help in making it efficient.

 Subsystem Validity − A model itself may not have any existing


system to compare it with, but it may consist of a known subsystem.
Each of that validity can be tested separately.
 Internal Validity − A model with high degree of internal variance will
be rejected as a stochastic system with high variance due to its
internal processes will hide the changes in the output due to input
changes.
 Sensitivity Analysis − It provides the information about the sensitive
parameter in the system to which we need to pay higher attention.
 Face Validity − When the model performs on opposite logics, then it
should be rejected even if it behaves like the real system.

Monte Carlo Simulation


Monte Carlo simulation is a computerized mathematical technique to
generate random sample data based on some known distribution for
numerical experiments. This method is applied to risk quantitative analysis
and decision-making problems. This method is used by the professionals of
various profiles such as finance, project management, energy,
manufacturing, engineering, research & development, insurance, oil & gas,
transportation, etc.

This method was first used by scientists working on the atom bomb in 1940.
This method can be used in those situations where we need to make an
estimate and uncertain decisions such as weather forecast predictions.

Monte Carlo Simulation ─ Important Characteristics

Following are the three important characteristics of Monte-Carlo method −

 Its output must generate random samples.


 Its input distribution must be known.
 Its result must be known while performing an experiment.
Monte Carlo Simulation ─ Advantages
 Easy to implement.
 Provides statistical sampling for numerical experiments using the
computer.
 Provides approximate solution to mathematical problems.
 Can be used for both stochastic and deterministic problems.

Monte Carlo Simulation ─ Disadvantages


 Time consuming as there is a need to generate large number of
sampling to get the desired output.
 The results of this method are only the approximation of true values,
not the exact.
Monte Carlo Simulation Method ─ Flow Diagram

The following illustration shows a generalized flowchart of Monte Carlo


simulation.

You might also like