Você está na página 1de 4

IE 603: Discrete Event System Simulation,

IIT Bombay

R is a free software environment for statistical computing and graphics. It is an


integrated suite of software for data manipulation, calculation and graphical display. Getting Started with R Open R. The white window you will see is the R console. Now let try some simple commands > x <- c(10.4, 5.6, 3.1, 6.4, 21.7) ! Creates a vector x > 1/x ! Computes reciprocal of all values of x. Can perform any such arithmetic operations > mean(x) ! Computes mean of x > sd(x) ! Computes std dev of x > sqrt(sum((x-mean(x))^2)/(length(x)-1)) ! Same as sd(x)? Many more in built functions are available. You can access the HTML help files by typing help.start() in R console and learn them on your own. Explanations on loops, basic outline etc can be found under An Introduction to R Explanations on various statistical function can be found under Packages> Stats Explanations on hist function can be found under Packages> Graphics Lets build our first simulation model to evaluate
!

Click File >> New Script Input the code as shown below in the blank script window

I = " sin xdx


o

#My first MCS ! Whatever follows # is a comment MCS1 <- function(n){ ! Defines function MCS1(n), n is sample size set.seed(3) ! Sets seed of random number generator to 3 eval_vector <- 1:n ! create a vector of size n, initialized to 0 for (i in 1:n){ v <- runif(1, 0, pi) ! generates 1 Uniform random variable between 0 and pi eval_vector[i] <- sin(v) } result <- pi*mean(eval_vector) print('Integral Mean') print(result) hist(pi*eval_vector) rm(eval_vector) } ! Display a histogram ! Remove the vector to free up memory

Save the script file as YourRollNumber.R


1

IE 603: Discrete Event System Simulation,

IIT Bombay

Run the Script: With focus in the script editor window, click from menu, Edit > Run all Your script will run in the RConsole window on left. It will be in Red color. If there are any error messages, it will appear in Blue in the Console. Now, Go to R Console Window. At the prompt, type > MCS1(10) and press Enter Results of print statements will be displayed as above. Name MCS1 is the name given to the function you have written in script (.R) file. Compute the integral estimates using Monte Carlo Simulation, for above integral, for sample size = 10, 100, 1000, 10000, 100000. Observe the histograms obtained. The above mean values are just point estimates. We need to bound the error between this sample mean obtained and the true mean we are interested in ! Lets use the measure of error: Confidence Interval (CI) of the Mean We know that: Suppose X1,Xn are i.i.d samples from a Normal population, then the 100*(1 !)% CI of the true mean is: When population variance !2 is known, When pop variance !2 unknown,

# X z" / 2

!
n

# X tn "1,! / 2

S n

Can we build a CI using the sample data generated in the above MCS1 function? Ans: NO ! Recall discussions in the earlier classes Modify the above code to create batches, and then use the batch means to construct a valid CI, as shown below. Copy the code below in a new script window #My second MCS MCS2 <- function(n, batchsize, alpha){ ! Defines function MCS2(n, batchsize, alpha), where n is the number of batches, batchsize is the samples per batch, and alpha to construct 100*(1 !)% CI set.seed(3) ! Sets seed of random number generator to 3 eval_vector <- 1:n batch <- 1:batchsize for (i in 1:n){ for (j in 1:batchsize){ v <- runif(1, 0, pi) batch[j] <- pi*sin(v) } eval_vector[i] <- mean(batch) }
2

IE 603: Discrete Event System Simulation,

IIT Bombay

result <- mean(eval_vector) print('Integral Mean') print(result) s <- sd(eval_vector) hist(eval_vector) rm(eval_vector) tvalue <- qt(alpha/2,n-1,lower.tail=FALSE) print('Halfwidth using t-distribution') hw <- tvalue*s/sqrt(n) print(hw) } Compute the integral estimates, with batchsize as 100 and number of batches as 10, 100, 1000. Observe the histograms obtained. Compute the integral estimates, with batchsize as 10, 100, 1000 and number of batches as 10. Observe the histograms obtained. Is it better to have a small number of batches, but each batch size is large -OR- to have a large number of batches, but each batch size is small. Test with configurations such that the total samples evaluated is constant at 10000. Profit of a Firm: A firms sells firm product X under a pure/perfect competition market (firm doesnt influence price). The total profit of the firm depends on its income and expense. The income depends on the quantity demanded and the price at which each product is sold. The expense is mainly determined by the production which involves a fixed cost as well as a variable cost per product produced. Now, the Quantity Demanded, Q is know to be Uniformly distributed in the range [8,000, 12000], the price of product P is Normally Distributed with mean 10, and standard deviation 3, truncated with min of 1. The fixed cost FC of production is Rs.5000. The Variable Cost, VC is Normally distributed with mean 7, and std dev 2, truncated on both sides with a min of 3.5 and a max of 10 The firm wants to know: (1) the mean profit. (2) the probability distribution for the profit of this product (3) the probability that the firm may lose money when marketing it. The pseudo code for the problem is given below. Implement it using R and answer the above questions.

IE 603: Discrete Event System Simulation,

IIT Bombay

FC = 5000 For i = 1 ! N Q(i) = UNIF(8000,12000) VC(i) = Sample from truncated normal(= 7, sd= 2, min= 3.5, max= 10) P(i) = Sample from truncated normal( = 10, sd = 3, min= 1) TP(i) = Q(i)*P(i) [(Q(i)*VC(i)) + FC(i)] Next i Exercises - Try the following and submit them via Moodle course page. 1. Airline Optimization:Consider flight IEX 306 that flies daily from Mumbai to Chennai. Flight has 100 seats. Price of a ticket is on an average Rs. 6000. There is 10% chance that a sold seat will remain vacant (i.e. passenger doesnt show up). Airline refunds 50% of the price of ticket to that passenger for such last minute cancellations. If the airline overbooks, then it pays an average of Rs.10000 for any passenger who is bumped (i.e. denied seat in plane). Daily demand for seats is Poisson distributed with mean 120. Now, the airline can decide to sell x tickets, where x can be more or less than the capacity of plane. What is the value of x (the number of tickets to sell) that maximizes the expected profit? 2. Finance: The following model is frequently used to mimic share price movement. Let Si denote the price of share at time ih where i = 0, 1, 2, and h is a positive time increment. Let and " denote growth rate and volatility respectively. Let

1 # $ h "$% & ' h 1 "e % e '% (" e# $ h% e"$% & ' h'2# 4 , 2 2 #1 v! u , $h e #v p! u# v u!
2 2

Then, Si =Xi Si-1 where Xi are independent Bernoulli random variables with P{Xi =u} = p and P{Xi =v} = 1-p , for all i. (i) Simulate & plot the movement of the share price for each week during the next one year, h = 1/52. Let S0= 100, = 0.2 per annum and " = 0.3 per annum. (ii) Simulate 20 such paths (with plots), and compute the average price of stock at the end of one year. 3. Area of Ellipse: Devise and implement a Monte Carlo Simulation procedure to calculate the area of the ellipse (x/a)2 + (y/b)2 = 1; a, b > 0. Does choice of a, b affect the accuracy of the results? Why or Why not? Note: a, b, to be inputs to the program
4

Você também pode gostar