Vous êtes sur la page 1sur 20

Chapter 20

Simulation Revisited

Chapter Overview

20.1 Introduction
20.2 Review of Chapter 9
20.2.1 Defining Simulation
20.2.2 Working with Distributions

20.3 Simulation with VBA


20.3.1 Random Numbers and Distributions
20.3.2 Making Runs and Collecting Data
20.3.3 Animation
20.3.4 Analysis

20.4 Applications
20.4.1 Game of Craps Revisited

20.5 Summary
20.6 Exercises
Chapter 20: Simulation Revisited

20.1 Introduction
This chapter illustrates to the reader how simulation can be performed, and enhanced, in
Excel using VBA. The reader will learn how to generate random numbers in VBA, make
runs and collect data using loop structures, add animation to their simulation, and
perform and display an analysis of the simulation. Many DSS applications may involve
simulation. We use simulation in our Reliability Analysis, Queuing Simulation, and
Capital Budgeting.

20.2 Review of Chapter 9


In Chapter 9, we defined simulation and discussed how to apply it in an Excel
spreadsheet. In this chapter we will show some parallel functionality that can be
accomplished using VBA. First, let us review how simulation is defined and how to work
with distributions when using simulation in Excel.

20.2.1 Defining Simulation

Simulation is a modeling tool which is used to imitate a real-world process in order to


understand system behavior. The true behavior of a system is estimated using
distributions. Random numbers from these distributions can be generated to evaluate
multiple strategies and predict future performance. Simulation is a useful tool in that it
can make observations from trial and error without the cost of materials, labor and time
that would be necessary to observe the same results on the original process. Simulation
differs from optimization in that instead of seeking to optimize an objective function
value, it simulates the behavior of a system to asses its performance under several
scenarios which may be used in what-if analysis.

20.2.2 Working with Distributions

Simulation can handle variables or parameters that are stochastic in nature. It models
stochasticity by generating random numbers from different distribution functions. We
have already seen the RAND function in Excel along with other distribution functions.
The general distribution function has the following format:

=DIST(x_value, distribution_parameters, cumulative_value)

For these parameters, the x-value is the number for which we want the distribution and
the cumulative value is TRUE if we use the cumulative distribution function (cdf), or
FALSE if we use the probability mass function (pmf). However, to generate a random
number within a given distribution, we must use the inverse functions of these
distribution functions. These inverse functions return the inverse of the cumulative
probability functions. That is, if probability = DIST(x,...), then DISTINV(probability,...) = x.

Some of the inverse functions of the more common distributions are BETAINV,
BINOMINV, LN or LOGINV (the Exponential inverse), and NORMINV. You can also find
these functions in the Statistical category of the list of functions when we choose Insert >
Function from the menu. The format of these inverse functions is:

=DISTINV(probability, distribution_parameters)

2
Chapter 20: Simulation Revisited

The probability parameter is a number between 0 and 1 associated with the given
distribution. We will use the RAND function as our value for this parameter to generate
some number between 0 and 1. For example, to generate random numbers from the
Normal distribution, we would follow the format:

=NORMINV(RAND(), mean, std dev)

We can use these functions to generate data which might be common in a given
scenario. We then analyze sets of this data to understand how our problem behaves.
We discussed using the Scenario program in Excel to analyze varying data values in
Chapter 9. However, in this chapter we will focus more on generating random data and
analyzing it.

Simulation: display of a process which one wants to analyze under different


parameters or settings

Summary Excel simulation: use RAND function and inverse functions, DISTINV, to
generate random numbers from a particular distribution

20.3 Simulation with VBA


When programming a simulation application in VBA, you can use any of these Excel
functions to generate random data. This would be done by placing an Excel function into
a range on the spreadsheet using the Formula or FormulaR1C1 methods. However, it
may not always be ideal to output all simulation data to a spreadsheet. The advantage of
using VBA in developing a simulation program is to use programming structures such as
arrays, For Loops, and Do Loops to increase the efficiency of working with large sample
data and performing analysis. In this section, we introduce some new VBA functions and
remind the reader of some previously discussed VBA functions which can be used to
generate random data from distributions for the purpose of simulation.

20.3.1 Random Numbers and Distributions

To generate random numbers in VBA, we will use the Rnd function as discussed in
Chapter 14. This function can be manipulated to generate a random number between a
lower bound and upper bound using the formula below (here the value of this random
number is assigned to an x variable):

x = (upperbound - lowerbound + 1) * Rnd() + lowerbound

This formula can also be used to generate a random number from the Uniform
distribution. You can use this formula with the Int function to ensure that this random
number is an integer.

x = Int((upperbound - lowerbound + 1) * Rnd() + lowerbound)

To generate a random number from the Exponential distribution, you can use the Log
function. To do this we just take the logarithm of a random number, using the Rnd

3
Chapter 20: Simulation Revisited

function, and multiply it by the negative mean value of a particular Exponential


distribution:

-Mean * Log(Rnd())

This mean value can also be represented by a variable. For example, we may set a
mean variable equal to an InputBox function which prompts the user for a mean of an
Exponential distribution which models their system. We can then use this mean value to
generate the appropriate data. For example, the code below generates 10 random
numbers from an Exponential distribution with a user-specified mean and stores the
values in an array:

Dim mean As Double, ExpValues(10) As Double


mean = InputBox(Please enter mean of your Exponential distribution.)

For i = 1 to 10
ExpValues(i) = -mean * Log(Rnd())
Next i

There is also a set of VBA functions available for generating random numbers from a
distribution which can be found among the Application.WorksheetFunctions. In this set of
worksheet functions are several of the inverse functions we used in Excel, such as:
NormInv, Ln, BetaInv, ChiInv, FInv, and GammaInv. The general format for using
these functions in VBA is as follows:

Application.WorksheetFunction.DistInv(probability, distribution_parameters)

The probability parameter can be replaced with the VBA Rnd function in order to
generate a random number from the distribution. One of the most common distributions
we will generate random numbers from is the Normal distribution. This would be done
using the NormInv function with the Application object:

Application.WorksheetFunction.NormInv(probability, mean, standarddeviation)

We can also prompt the user for the mean and standard deviation values to create the
following dynamic code:

Dim mean As Integer, stdev As Integer


mean = InputBox("Enter mean:")
stdev = InputBox("Enter standard deviation: ")

MsgBox "A random number from the normal distribution with mean " _
& mean & " and standard deviation " & stdev & _
"is " & Application.WorksheetFunction.NormInv(Rnd(), mean, stdev)

Distribution VBA function


Uniform (b a + 1)*Rnd() + a
Summary
Exponential -mean*Log(Rnd()), Application.WorksheetFunction.Ln

Normal Application.WorksheetFunction.NormInv

Beta Application.WorksheetFunction.BetaInv
4
Chi-Squared Application.WorksheetFunction.ChiInv

F Application.WorksheetFunction.FInv
Chapter 20: Simulation Revisited

20.3.2 Making Runs and Collecting Data

As seen in the code above, we can use For, Next loops to generate multiple data values.
Instead of generating only 10 data values, we may ask the user to specify how much
data they want to use for the simulation. We may also perform some calculations with
the random data we generate.

For example, suppose there is a system which takes as input a number from an
Exponential distribution with lambda 5, and outputs the square of that number. In our
For, Next loop we would need to generate a series of random numbers and also
calculate their square. The user may then want to analyze the distribution of this output.

To simulate this system, we would first prompt the user for the number of runs they want
to perform. A run is a single execution of a series of actions which model the system. We
then need to determine if we will be storing this data and the results of the specified
calculations in arrays or in a spreadsheet. When multiple calculations of data are
needed, which do not require Excel functions, arrays can be easier structures to work
with. They are easier in the sense that range names do not need to be defined and extra
worksheet space does not need to be used. If, however, some other Excel functions,
such as distribution functions, will need to be used with the generated data, it may be
better to store this data in a worksheet.

For this example, we can use the Log and Rnd VBA functions to generate the data in the
Exponential distribution and we can perform the squaring calculation in VBA as well. We
will therefore use arrays. We may perform the simulation for this example using the
following code (we assume all arrays to be Option Base 1):

Dim runs As Integer, Input() As Double, Output() As Double


runs = InputBox(Please enter the number of runs for this simulation.)

ReDim Input(runs)
ReDim Output(runs)

For i = 1 to runs
Input(i) = 5 * Log(Rnd())
Output(i) = (Input(i)) ^ 2
Range(A1).Offset(i,0).Value = Output(i)
Next i

The input and/or output of a simulation can then be stored in a spreadsheet for the user
to see. For some simulation models, it will be unnecessary to store or show the user the
input values; analysis of the output is usually of most importance to the user.

5
Chapter 20: Simulation Revisited

20.3.3 Animation

Two other VBA methods should be used when creating a simulation program are the
ScreenUpdating and Wait methods of the Application object (as discussed in Chapter
13). The ScreenUpdating method should be set to False before the simulation runs
begin. This reduces screen flickering while the program runs and increase efficiency
(due to decreased running time) if the screen is not updated after every action in the
code. It should be set to True when the runs have been completed.

The Wait method can be used to create some animation of the simulation. For example,
if we are simulating a production line, we may have several parts being received and
shipped from different work stations. Each of these work stations may have a different
distribution for processing time. We can use the functions discussed above to create a
list of generated time values at which a part is finished at each station. That is, if Work
Station 1 processes parts at an Exponential rate of 2, then we could use the following
code to generate times at which parts would leave Work Station 1:

ReDim WorkStation1(runs) As Double

For i = 1 to runs
WorkStation1(i) = 2 * Log(Rnd())
Next i

Here, runs could be equal to the number of parts which pass through the system in one
work day. We can consider each value of our WorkStation1 array to be a time value. We
can then create a cumulative time array using the following:

ReDim CumWork1(runs) As Double

WorkStation(1) = 0
For i = 1 to runs
CumWork1(i) = WorkStation1(i) + WorkStation1(i 1)
Next i

Now, we can run a loop to show that a product leaves Work Station 1 at each time value.
To do this, we may highlight some cell which changes position, or disappears and
reappears, every time this action occurs. To create this action, we would pick some
range to highlight (by changing the color with the Interior property) and each time we
loop through a run, we un-highlight this cell and highlight the next cell (using the Offset
property). However, to ensure that the user sees a delay between these actions, we use
the Wait method. [Note that we will now need to move the ScreenUpdating statement
inside the loop so that the user sees the highlighted cell each iteration.] It may be a good
idea to display the time at each event as well. The corresponding code would be as
follows:

For i = 1 to runs
Application.ScreenUpdating = False
Range(Time).Value = CumWork1(i)
Range(A1).Offset(i-1, 0).Interior.ColorIndex = 0
Range(A1).Offset(i, 0).Interior.ColorIndex = 5
Application.Wait(Now + TimeValue(0:0:03))

6
Chapter 20: Simulation Revisited

Application.ScreenUpdating = True
Next i

Running this code will create an animated simulation which appears to move a product
from one cell to the next at each iteration. This idea can be modified to create an
animation that better reflects any particular system.

20.3.4 Analysis

The motivation for using simulation is of course to perform some analysis on a system.
There are several ways to analyze the results of a simulation. For the output produced, a
graph can be created, the maximum or minimum can be found, etc. These actions can
be accomplished using the Chart object as seen in Chapter 13, or any of the
mathematical functions shown in Chapter 14.

Another powerful analysis tool available in Excel is the Data Anlaysis Toolpack. We
discussed some of the analysis tools available in this Add-In in Chapter 9; the tool we
discussed in most detail was the histogram. Histograms calculate the number of
occurrences, or frequency, which values in a data set fall into various intervals. When we
created histograms in Excel using the Data Analysis Toolpack, we had to provide
several parameters: an input range of data, a range for bin values (optional), and an
output range for the histogram results. We also had to check if we wanted to show data
labels, create a pareto chart, calculate cumulative values, and display a chart of the
histogram results. The bin range is used to specify the location of the bin values, where
bins are the intervals into which values can fall. If no bin range is specified, Excel
automatically calculates a set of evenly distributed bins.

To create a histogram using VBA, we will use the Application object and the Run
method. The Run method is used to specify the Add-In file from which we will be running
the analysis. The arguments for this method include all of the parameters we specified
when creating a histogram in Excel:

Application.Run "ATPVBAEN.XLA!Histogram", InputRange, OutputRange,


BinRange, Labels, Pareto, Cumulative, Chart

The values for the InputRange, OutputRange, and BinRange parameters should be
ranges. These ranges can be named in Excel or they can be range variables in VBA.
The Labels, Pareto, Cumulative, and Chart parameters all take True/False values.

This simple line of code can be used on dynamic input ranges to create a histogram for
different sets of user data. Note, however, that if you run this code multiple times with
the Chart parameter set to True, you will have multiple charts created on the
spreadsheet. For better code efficiency, we recommend creating a histogram in Excel
first (as we have seen with some Chart applications) and then modifying your code so
that all of the chart option parameters are set to False. As you repeat this code to run a
histogram analysis on different sets of input values, you may see a warning message
that your output range will be overwritten. We therefore recommend adding a line of
code to clear this output range of cells before creating the histogram multiple times.

7
Chapter 20: Simulation Revisited

Other analysis from the Analysis Toolpack may be useful to your application. To
discover the particular code and parameters for each analysis tool, record a macro first
in Excel (most analysis tools will still run an extension of the ATPVBAEN.XLA file).

Animating simulation with VBA:


Application.ScreenUpdating
Application.Wait(Now() + TimeValue(00:00:01))
Summary

Analysis using Histograms:


Application.Run "ATPVBAEN.XLA!Histogram", InputRange, OutputRange,
BinRange, Labels, Pareto, Cumulative, Chart

20.4 Applications
20.4.1 Game of Craps Revisited

In Chapter 9, we described a Craps game simulation in which we were trying to


determine how often a player wins or loses in up to 5 rolls of the dice. In the game of
Craps, a player rolls two dice. If the first roll yields a sum of 2, 3, or 12, the player loses.
If the first roll yields a sum of 7 or 11, the player wins. Otherwise, the player continues
rolling the dice until she matches the value thrown on the first roll or rolls a sum of 7.
Rolling a match for the first roll wins the game, rolling a value of 7 before a match loses
the game.

We will now rebuild this simulation using VBA to allow us to perform more runs and
include some animation. We will show the user the value of the dice they roll on each
run; each run is defined to be one play of the game with one to five rolls of the dice. After
each roll of the dice, we evaluate the value of the sum to determine if they continue
rolling or stop the game by winning or losing (again, we are assuming a maximum of five
rolls possible for now). We will also display to them whether they won, Won!, lost,
Lost, or need to continue rolling past the fifth roll, . (see Figure 20.1).

8
Chapter 20: Simulation Revisited

Figure 20.1 The new Craps Simulation has images of the dice and the sum of their
values for each roll.

For each run, we will keep statistics of the run number, if the player won or lost within the
five rolls, and how many rolls they played until this win or loss occurred. We will also
store if they rolled five dice and still needed to continue rolling; that is, no win or loss
occurred in five rolls. We denote this by recording a instead of Win or Lose and
we record the number of rolls as 6 (any number greater than 5). In Figure 20.2, we show
the statistics for 20 runs.

When the simulation is completed, we will use these statistics to create two histograms:
the frequency with which a player wins in 1, 2, 3, 4, or 5 rolls and the frequency with
which they lose in the same number of rolls. Notice in the figure that we have copied the
statistics and sorted them by wins and losses to separate the data for the two
histograms. We have also forced the bins to be 1, 2, 3, 4, and 5 by specifying a bin
range when creating the histograms (this range is hidden on the spreadsheet).

9
Chapter 20: Simulation Revisited

Figure 20.2 Statistics are kept for each run and two histograms are created.

Let us now take a look at the initial code. We will begin with a Start procedure. This
procedure will initialize necessary variables, clear previous values, prompt the user for
the number of runs to perform, and call a loop to repeat the actions for this given number
of times. When the simulation is complete, we will also call a procedure to create the
histograms (see Figure 20.3).

We have some range variables we will use for each dice roll. We use these ranges to
paste the dice images, display the sum values, and clear previous data. As an
alternative to some of the range variables we have used in the past, for this application
we have created an array of ranges for our variables. We define the array Rolls() to
contain the five ranges we will use to identify each dice roll. We have chosen to use an
array in this case so that we can refer to the rolls by an index number in later code. That
is, instead of referring to FirstRoll, SecondRoll, etc. as range variable names, it will be
easier for us to refer to Rolls(1), Rolls(2), etc. This way, we can use some loops to
repeat actions that will occur for each roll and to each roll range. We therefore begin our
Start procedure by setting the ranges in the Rolls() array to ranges on the spreadsheet
(offset by 2) using a For, Next loop. We also set references for two more range
variables: Stats and Hist, referring to the beginning of the statistics and histogram tables,
respectively.

10
Chapter 20: Simulation Revisited

Figure 20.3 The Start, ClearPrev, and ClearImages procedures.

We then prompt the user for the number of runs, which we set equal to an integer
variable NRuns. We then use this variable in a For, Next loop to call repeatedly the
procedure for playing the game in each run. This procedure is called PerformSim. We
will also clear the images from the previous run in this loop and cause a slight delay to
enhance the animation. We cause the delay using the Application.Wait method. When
the loop has finished and the simulation is complete, we create the histograms by calling
the CreateHist procedure.

The ClearPrev procedure clears all images, statistics, and histogram data. The
ClearImages procedure clears all previous dice images and sum values. Clearing
images can be somewhat tricky in VBA. We have used the Delete method and
xlShiftToLeft arguments to move all of the images to the first column in the spreadsheet.
We then use the Cut method to remove these images completely and paste them on to
another sheet containing the dice images.

11
Chapter 20: Simulation Revisited

Let us now look at the main simulation procedure, PerformSim (see Figure 20.4). In this
procedure we want to roll the dice and evaluate the sum of the values to determine if
more rolls are necessary. Our criteria for determining a win or loss is different for the first
roll than for the other rolls, so we will separate the two checks. We use an If, Then
statement to determine if the result of the first roll is a win or loss. If this is the case, we
display the result to the user and record the run number and roll number in the statistics.
We then use the Exit Sub statement since no more rolls are needed after a win or loss is
encountered. However, if no win or loss is found after the first roll, we can move on to
checking the second set of criteria for all subsequent rolls. This second criteria will use
the sum value from the first roll as a check for winning. If a win or loss is found in any of
these rolls, the result is displayed, the statistics are recorded, and the run ends just as in
the first roll. If all five rolls are completed without finding a win or loss, then statistics are
recorded as a with roll number 6.

12
Chapter 20: Simulation Revisited

Figure 20.4 The PerformSim procedure checks for a win or loss after each roll.

For each roll, we will need to perform a repeated set of actions. We will need to generate
a random number between 1 and 6 for each dice, copy and paste their corresponding
images, and find the sum of their values. We have created a function, RollDice to do this
(see Figure 20.5). The only input we need for this function is the roll number. We need
this value in order to paste the dice images and display the sum value in the correct roll
range.

13
Chapter 20: Simulation Revisited

Figure 20.5 The RollDice and GetImages functions are called for each roll.

To copy and paste the images, we will use another function called GetImages. We have
stored some dice images on another sheet which we will copy and paste in the
appropriate spot for each roll (see Figure 20.6). We have arranged these images so that
we can use the offset property with the title range Images to find the dice image
matching the number rolled. That is, if the roll was a 1 and 3, then the images we need
can be found by:

Range(Images).Offset(0,1)
Range(Images).Offset(0,3)

Figure 20.6 The images of all six dice are stored to use for the animation.

Therefore, we need to pass to the GetImages function the value of each dice and the roll
number. We use the dice values to find the images and the roll value to paste the
images. Note that we have used the ActiveSheet.Paste method instead of the
Range.PasteSpecial method since we are working with images.

The loop for checking the criteria of the second through fifth rolls has been simplified by
using the Rolls() range array. We have created the RollDice and GetImages functions
such that all we need is the index of the Rolls() array to modify the appropriate roll
range.

After the rolls are made and statistics recorded for each run, the simulation is complete.
We are now ready to analyze the statistics by creating histograms. The first thing we do
in the CreateHist procedure is copy and sort the statistics data (see Figure 20.7). We
want to define a range for the winning data and one for the losing data to use as input for
the two different histograms. We sort the data and then scan through the list to separate
the status values Win and Lose. We name the separated ranges Wins and Losses
respectively.

14
Chapter 20: Simulation Revisited

We can now create the two histograms by using the Application.Run ATPVBAEN.XLA
!Histogram statement. The arguments for this statement are: input range, output range,
bin range, and some options for creating labels, charts, pareto, and cumulative values.
The input ranges have just been named, Wins and Losses, and we use the Hist
range variable to locate the output range. We have created a range called Bin, hidden
on the spreadsheet, which contains the bin values 1, 2, 3, 4 and 5 in a column. We will
use this bin range to force the frequency calculations done by the histogram program. As
we recommend when using charts, we will not recreate the histogram charts in the code.
We have already run the histogram program once in the spreadsheet to create the initial
charts. We have formatted them and given them appropriate titles. We can therefore set
the histogram options to all be false, as the histogram output range will not change and
so the charts will be updated each time.

Figure 20.7 The CreateHist procedure manipulates the statistics data and creates two
histograms.

The application is now complete. We can start the code by assigning the Start procedure
to the START button. (Note: Can you extend this application so that it is not limited to
five rolls?)

20.5 Summary
Simulation is a modeling tool which is used to imitate a real-world process in order
to understand system behavior.

15
Chapter 20: Simulation Revisited

Simulation can handle variables or parameters that are stochastic in nature. It


models stochasticity by generating random numbers from different distribution
functions.
We use the RAND function and other distribution functions in Excel to generate
data for a simulation. To generate a random number within a given distribution,
we must use some inverse functions.
To generate random numbers in VBA, we will use the Rnd function. You can use
this equation with the Int function to ensure this random number is an integer.
To generate a random number from a particular distribution in VBA, we can use
the inverse functions from Excel. We insert these functions into ranges using the
Formula or FormulaR1C1 methods in VBA.
The Log function can be used with the Rnd function in VBA to generate random
numbers from the Exponential distribution. To specify a particular Exponential
distribution from which the random number is being generated, we simply multiply
the mean by the functions: -mean * Log(Rnd()).
The Application.WorksheetFunction method contains several inverse functions
which can be used directly in VBA.
We use For, Next loops to generate multiple data values. To simulate this system,
we would first prompt the user for the number of runs they want to perform. A run
is a single execution of a series of actions which model the system.
We need to determine if we will be storing this data and the results of the
specified calculations in arrays or in a spreadsheet. When multiple calculations of
data are needed, which do not require Excel functions, arrays can be easier
structures to work with. If, however, some other Excel functions, such as
distribution functions, will need to be used with the generated data, it may be
better to store this data in a worksheet.
The ScreenUpdating method should be set to False before the simulation runs
begin. It should be set to True when the runs have been completed.
The Wait method can be used to create some animation of the simulation. To
ensure that the user sees a delay between actions, we use the Wait method.
The Analysis Toolpack can be used to perform many types of analysis. This Add-
In can be run in VBA using the Application object.
Histograms calculate the number of occurrences of values in a particular interval.
There are four main parts to creating a histogram: input, bins, output, and charts
options.
Use the Application object and the Run method in VBA to specify the Add-In file
from which we will be running the analysis. The arguments for this method include
all of the parameters of the analysis tool.

20.6 Exercises
20.6.1 Review Questions

1. How to you generate random numbers from an Exponential distribution?


2. What other distributions have inverse functions associated with the Application object
(and WorksheetFunction method)?
3. If using the Application.WorksheetFunction.NormInv() function, how do you specify a
random probability value?
4. What is the code used to deactivate and reactivate the screen updating functionality
in VBA? Give an example of when this code would be useful.

16
Chapter 20: Simulation Revisited

5. Write the VBA code to delay a VBA program for 10 seconds.


6. Discuss how the Wait method and ScreenUpdating property are useful in simulation
programs.
7. How can animation be an important part of a simulation program?
8. Consider a simulation program that has animation. Is it possible to build the program
so that the user has the ability to pause or stop execution at any time without causing
an error?
9. What can your simulation program do in order to improve the accuracy and
dependability of the results?
10. What is the code to generate a histogram?

20.6.2 Hands-On Exercises

1. Extend the Craps Simulation application so that it is not limited to five rolls.

2. Create an interactive program where the computer flips a coin and the user must
choose heads or tails. The program should keep track of how many times the
game was played, what the users choice was each game, and the games
outcome.

3. A coffee shop has three workers preparing coffee orders for a single register.
Customers arrive exponentially with a mean inter-arrival time of 1 minute. There is
a single queue to order a drink, and the workers can complete an order according
to a exponential distribution with mean of 5. The shop is open 16 hours per day.
Simulate the system for a 16-hour day and count the number of orders processed.

4. Companies often want to track their sales data in order to assist them in
forecasting future sales of similar products. Using the following table of sales
data, create a forecasting tool that allows the user to input new data (which
should be added to the historical data) and simulate a forecast for a future period
using the data provided.

sales data
1
3
3
5
6
9
5. Create a simulation program in which the computer and user play the card game
of War. Be sure that the user is informed of the status of play throughout the
game. The rules for the game are as follows:

52 Cards are dealt, 26 cards to each player


In each round of play, both players present their top card. The card with the
highest value wins, and the player places both cards on the bottom of his
deck. (The order of precedence from lowest to highest is 2-10, Jack, Queen,
King, and Ace.)

17
Chapter 20: Simulation Revisited

If both players present a card of the same value, each player places 4 cards
face down in front of them and plays the 5th card to win all 12 cards. This is
called a war.
Play ends when one player has all 52 cards.

[Hints: Use arrays to set up each players deck of cards. The size of each array
will vary throughout the course of the game. Also, when dealing the cards, dont
forget to shuffle the deck! For ease of coding, call the Jack, Queen, King and
Ace cards by the numerical values 11, 12, 13, and 14.]

6. Create a program that allows a user to control the movements of an object on a


worksheet from cell to cell. The program should perform the following actions:
a. Initializes an object with a background color and a border around it and
locates it approximately in the center of a worksheet.
b. Asks the user for a string of letters which gives the directions for moving the
object. The following letters give the corresponding direction of movement:
U is Up, D is Down, L is Left, and R is Right. Any other character does
not cause the object to move. Below is an example of an input and the
resulting movements.

Input: DLLDR URR


Movements: Down, Left, Left, Down, Right, No Movement, Up, Right, Right

c. Moves the object according to the users input until finished or the object
cannot move in the given direction. Use a one second delay between
characters.
d. Display an appropriate message.

7. Dice Statistics: Suppose we toss an ordinary die 5 times. A 4-straight occurs if


exactly 4 (not 5) of our rolls are consecutive integers. For example, if we roll 1, 2,
3, 4, 6, we have a 4-straight.
a. Run a simulation for 100, 1,000, and 2,000 iterations.
b. For each simulation, find a 95% confidence interval for tossing a 4-straight.
c. Repeat parts (a) and (b) for a 3-of-a-kind (ex: 1, 1, 1, 2, 3)

8. Create a program that allows a user to simulate buying and selling shares of
Finch Mutual Fund. A user may choose to buy or sell shares or to simulate the
next day without any transaction. When making a decision to buy or sell shares,
the user provides the number of shares and then pushes either a Buy button or
a Sell button. The transaction takes place before the next close of trading. The
share price at the time of transaction differs from the previous closing price
according to a Normal distribution with an average of $0.50 and a standard
deviation of $0.20. The share price has an equal chance of either increasing or
decreasing. The closing price for each day is calculated the same way. The
volume traded each day follows a Normal distribution with an average of 250
shares with a standard deviation of 50 shares. Implement two charts for the user
to view the closing share price and volume traded for the past 30 business days
as each day is simulated.

Use one table to keep information on the closing share price and volume for the
past 30 business days. Use another table to record transactions: shares traded,

18
Chapter 20: Simulation Revisited

bought or sold, total shares held after transaction, any profits or losses. The initial
share price is $42.

9. Create a program that allows a user to simulate a production facility for Micro
Circuits, Inc. which produces circuit boards for computers. The program will
simulate 12-hour work days. The probability of a production failure occurring
during a workday increases each day according to an Exponential distribution with
an average of 0.75%. When a failure occurs, required maintenance is performed
the same day. Preventative maintenance is performed at the request of the user.
On the worksheet, place a command button to allow the user to simulate the next
day and another command button to perform preventative maintenance before the
next day.

Maintenance Type Required Preventative


Time Production Halted, ~ Normal(30, 5) ~ Normal(10, 2)
minutes
Probability of Failure After Reduced by Half 2%
Maintenance
Maintenance Costs ~ Exponential($20) ~ Exponential($15)

Use a worksheet to keep records for each day: day number, number of failures,
maintenance costs, maintenance time, number of hours in production, number of
circuit boards produced, predicted profit for circuit boards produced. Use a chart
to plot the number of failures, number of circuit boards produced, or predicted
profit depending on the command button selected by the user. Assume a
production rate of 30 circuit boards per hour and an expected profit of $35.00 per
circuit board.

10. Six months before its regional conference, the Institute of Industrial Engineers
(IIE) must determine how many rooms to reserve for students in the university
hotel. At this time, IIE can reserve rooms at a cost of $50/room. IIE must pay the
$50 room cost even if the room is not occupied. IIE believes that the number of
students attending the conference will be normally distributed with a mean of
5,000 and a standard deviation of 1,000. If the number of people attending the
conference exceeds the number of rooms reserved, extra rooms must be
reserved at a cost of $80/room.
a. Use simulation to determine the number of rooms that should be reserved
to minimize the expected cost to IIE.
b. Allow the user to resolve the problem with different parameters for the
normal distribution.
c. Allow the user to resolve the problem with different room costs.

11. A drug company ABC is trying to take over another drug company XYZ. The
worth of XYZ depends on the success or failure of several drugs under
development. ABC does not know the actual worth of XYZ, but the current owners
of XYZ do know their actual worth per share. ABC assumes that XYZs actual
worth is equally likely to be between $0 and $100 per share. XYZ will accept
ABCs offer if it exceeds the true worth of the company. If XYZ accepts ABCs bid,
ABCs corporate strengths immediately increase XYZs market value by 50%. Use
simulation to determine how much ABC should bid.

19
Chapter 20: Simulation Revisited

12. The game Try Your Luck is played as follows: the user picks a number between
1 and 6 and tosses three dice. If the number does not appear, the user loses $1.
If the number appears x times, the user wins $x.
a. Develop an animated program for this game. Create a small user form with
a spin button to allow the user to choose his number. Use dice images (as
in the Craps Simulation) to illustrate the random toss of three dice.
b. Determine, on the average, how much money will the user win or lose on
each play of the game.

13. A soda company, KOOLOFF, is giving away a prize by selling bottles with letters
under the bottle caps. To win the prize, you must collect caps with letters which
spell the company name. In production, letters are randomly selected and placed
on the bottle caps. Create a program which does the following:
a. Animate the selection of bottle cap letters. Keep selecting bottle caps until
all six of the necessary letters have been collected. (Letters are randomly
and independently selected from the alphabet to be inserted into the bottle
caps.)
b. Perform this simulation several times (without the animation) to determine,
on the average, how many sodas need to be bought in order to win the
prize.
c. How much would the prize need to be worth in order to play the game
without loosing money on all the sodas bought? (Assume that each soday
costs $1.00.)

14. A manufacturer is trying to determine its annual profit. It estimates that it is


equally likely that annual unit sales will be low or high. If sales are low (60,000
units), the company can sell the product for $10/unit. If sales are high (100,000
units), a competitor will enter and the company can sell the product for only
$8/unit. The variable cost per unit has a 25% chance of being $6, a 50% chance
of being 47.50, and a 25% chance of being 49. Annual fixed costs are $30,000.
a. Use simulation, with many runs, to determine the expected annual profit.
b. Make this program dynamic by allowing a user to do the following:
i. Try a different estimate on sales. (It is currently estimated to follow a
Uniform distribution between 60,000 and 100,000 untis.)
ii. Try different variable costs for 25%, 50%, and 25% of the time.
iii. Try different variable costs at different percentages of the time
(ensure that these percentage values sum to 100%.)

15. Two leading pharmacy stores, EZ and WD, are trying to be top in the market.
Each week, a usual pharmacy store shopper goes to EZ once or WD once. If a
shoppers last visit was to EZ, then this shoppers next purchase will be at EZ with
probability 0.9; otherwise they will go to WD. Similarly, if a shoppers last visit was
to WD, then this shoppers next purchase will be at WD with probability 0.8;
otherwise they will go to EZ. Currently, half of the pharmacy store shopping
population visit EZ and half visit WD.
a. Simulate one year of sales an estimate each stores average weekly market
share. Assume that the total market size is 1,000 customers. (Hint: use the
Binomial distribution.)
b. Animate this simulation by having an image for each store and keeping
track of the number of weekly visitors to the store below it.

20

Vous aimerez peut-être aussi