Question2. The Public Service Answering Point (PSAP) in San Francisco employs \(19\) operators in \(8\)-hour shifts to process \(911\) calls. There are at least \(5\) operators always answering calls. The number of calls processed per operator can be modeled with a Poisson random variable with rate \(\lambda_0 =20\) calls per hour.

Quesion 2 (a) What is the probability an operator can process 20 calls in an hour? Repeat for 30 calls in an hour?

#Answer 2a
lambda <- 20

prob_20 <- dpois(20, lambda)

prob_30 <- dpois(30, lambda)

cat("Probability for processing 20 calls in an hour: ", prob_20, "\n")
## Probability for processing 20 calls in an hour:  0.08883532
cat("Probability for processing 30 calls in an hour: ", prob_30, "\n")
## Probability for processing 30 calls in an hour:  0.008343536

Quesion 2 (b) Given that 240 calls occurred in an hour, what is the probability that the ten operators can process them all assuming they are split equally among the operators?

#Answer 2b
# 240 / 10 = 24 calls per operator and have to assume all are processed.
greater_than_23 = 1 -ppois(23,20)
greater_than_23
## [1] 0.2125072
cat("Probability that 10 operators can process 240 calls: ", greater_than_23, "\n")
## Probability that 10 operators can process 240 calls:  0.2125072

Quesion 2 (c) Now, If the aggregate call rate per hour \(\lambda_c\) , is measured by \(\lambda_c = 85\) calls per hour, what is the probability of more than \(100\) calls in an hour

#Answer 2c
lambda <- 85
calls <- 100

prob <- 1 - ppois(calls, lambda)
cat("Probability for more than 100 calls per hour: ", prob, "\n")
## Probability for more than 100 calls per hour:  0.04934533

Question 3. For the two random number generator below A and B(don’t forget to add your R code)

- [A] \(Z_i = (9Z_{i-1} + 1) \mod 16\) with \(Z_0 = 5\).

- [B] \(Z_i = (7Z_{i-1} + 3) \mod 32\) with \(Z_0 = 10\),

Quesion 3 (a) Compute \(Z_i\) and \(U_i\) for values of \(i\) until a number is repeated, what is the period of both the generator? Provide your comments about the period of both RGN

#Answer 3a
Z_i <- 5
period_a <- 0
seq_a <- c(Z_i)

while(TRUE)
  {
  Z_i = ((9*Z_i + 1)%% 16)
  period_a <- period_a + 1
  
  if(Z_i %in% seq_a)
  {
    break
  }
  seq_a <- c(seq_a, Z_i)
  
}

Z_j <- 10
period_b <- 0
seq_b <- c(Z_j)

while(TRUE)
  {
  Z_j = ((7*Z_j + 3)%% 32)
  period_b <- period_b + 1
  
  if(Z_j %in% seq_b)
  {
    break
  }
  seq_b <- c(seq_b, Z_j)
  
}

#cat("Sequence [A]:", seq_a, "\n")
cat("Period [A]:", period_a, "\n")
## Period [A]: 16
#cat("Sequence [B]:", seq_b, "\n")
cat("Period [B]:", period_b, "\n")
## Period [B]: 8

Quesion 3 (b) Which of these parameters effect the period of LCG – \(a\), \(b\), \(Z_0\)

#Answer 
cat("The parameters that effect the period of LCG seem to be a and b.")
## The parameters that effect the period of LCG seem to be a and b.

Quesion 3 (c) For both generators plot a scatter diagram of the Zi values 1 apart. What are your observations from these plots? What do you think about the property of randomness of these generators?

#Answer
#Generator A
plot(seq_a[-length(seq_a)], seq_a[-1], xlab = "Z_i", ylab = "Z_i+1" )

#Generator B
plot(seq_b[-length(seq_b)], seq_b[-1], xlab = "Z_i", ylab = "Z_i+1" )

cat("Observations: The scatter diagrams seem to be very diverse. The relation between each point proves to be very random as the points are scattered across the plot. However, scatter diagram A has a slight pattern as the points are placed diagonally. On the other hand, generator B gives off no distinct pattern.  ")
## Observations: The scatter diagrams seem to be very diverse. The relation between each point proves to be very random as the points are scattered across the plot. However, scatter diagram A has a slight pattern as the points are placed diagonally. On the other hand, generator B gives off no distinct pattern.

Quesion 3 (d) Randomness of default random generator of R – Run runif command to generate 100 random numbers and plot the scatter diagram of these numbers ( values 1 apart) and discuss your observations about randomness of this random generator.

#Answer
random_num <- runif(100)

plot(random_num[-100], random_num[-1], col = "red", xlab = "Random # i", ylab = "Random Number for i + 1", main = "Scatter Diagram for Default Random Number Generator")

cat("Observations: There seems to be a uniform distribution, however, there is not a specific pattern. This supports the belief of truly random selections, as the data seems to be independent of each other and randomly scattered.")
## Observations: There seems to be a uniform distribution, however, there is not a specific pattern. This supports the belief of truly random selections, as the data seems to be independent of each other and randomly scattered.

Quesion 3 (e) Compute the mean value of \(U_i\) across the period

#Answer
mean_a <- mean(seq_a / 16)
mean_b <- mean(seq_b/ 32)

cat("Mean for [A]: ", mean_a, "\n")
## Mean for [A]:  0.46875
cat("Mean for [B]: ", mean_b, "\n")
## Mean for [B]:  0.421875

Quesion 3 (f) By providing a plot of density (histogram) discuss the uniformity of both of the generators

#Answer
#Generator A
hist(seq_a[-1] / 16, main = "Density Plot for [A]",
     xlab = "Value", ylab = "Density", col = "blue")

#Generator B
hist(seq_b[-1] / 32, main = "Density Plot for [B]",xlab = "Value", ylab = "Density", col = "red")

cat("Observations: For the first density plot, it proves to be very uniform. On the other hand, the second density plot seems to have density around 1, however, at some ranges there is a spike to 2. ")
## Observations: For the first density plot, it proves to be very uniform. On the other hand, the second density plot seems to have density around 1, however, at some ranges there is a spike to 2.

Question 4. Using the inverse transform method

Question 4.(a) Develop an algorithm for the random variable with cumulative distribution function F(x) below.

\[ F(x) = 1 - e^{-(x/\lambda)^k} \]

where \(x \geq 0\), \(\lambda \geq 0\), and \(k \geq 0\).

# Answer 4a
# This might be hard to print using R - you can write the step in your notebook and then include image here / or you can include as seperate file when upload

# Check if the IRdisplay package is already installed
if (!require(IRdisplay, quietly = TRUE)) {
  # If not installed, install it
  install.packages("IRdisplay")
  
  # Load the IRdisplay library
  library(IRdisplay)
} else {
  # If already installed, just load the library
  library(IRdisplay)
}


# Embed an image
display_jpeg(file = "Question4a.jpg")
## Warning in getOption("jupyter.base_display_func")(data, metadata): IRdisplay
## can only be used from the IPython R kernel and R magic.

Quesion 4 (b) Use the first three Ui values from part (a) and generator [A] of previous problem to create 3 values from the random variable when, \(\lambda = 1\), \(𝑘 = 5\)

#Answer
lambda <- 1
k <- 5
# 0.3125, 0.875, 0.9375 first 3 values. 
U <- c(0.3125, 0.875, 0.9375)
X <- (-log(lambda-U))^(1/k)
print(X)
## [1] 0.8217415 1.1576822 1.2262446

Quesion 4 (c) sing R generate 10,000 values from your algorithm when = 1 , 𝑘 = 5 and plot a histogram of the density. Discuss what insights you obtain when you look at the plot generated here vs the plot you generated in question 3 (e)

#Answer
generated_val <- runif(10000)
Xi <- (-log(lambda-generated_val))^(1/k)
hist(Xi, main = "Inverse Transform Diagram", freq = FALSE, col ="green")

cat("Observations: The histogram here tends to show a slightly skewed distribution. There is a hint of normal/symmetric distribution, however, it can be argued that there is a slight skewness. Comparing this to 3f, the graphs are very different as one proves to be uniform and the other has skewness (unimodal).")
## Observations: The histogram here tends to show a slightly skewed distribution. There is a hint of normal/symmetric distribution, however, it can be argued that there is a slight skewness. Comparing this to 3f, the graphs are very different as one proves to be uniform and the other has skewness (unimodal).

Question 5. Develop a Monte Carlo simulation in R that counts the number of uniform [0,1] random numbers that must be summed to get a sum greater than 1. Run a single simulation with n = 10,000 times and find the mean of the number of counts. Do you think this number looks somewhat familiar. Every student might get slightly different value any ideas why?

#Answer
n <- 10000
#Initializes an open vector
vec <- rep(0,n)
range <- 1:n
sum <- 0
count <- 0
for (i in range) {
  # Creates an infinite loop without the need of while to have condition.
  repeat{
    condition = runif(1)
    sum = condition + sum
    count = count + 1
  
    if (sum > 1)
    {
      break
    }
  }
  
  vec[i] <- count
  sum <- 0
  count <- 0
  
}

mean_of_count <- mean(vec)

cat("Mean of the number of counts: ", mean_of_count, "\n")
## Mean of the number of counts:  2.7324
cat("Interpretation: I noticed that the value hovers around 2.7 which is quite similar to the number e. Every iteration is different due to the random choice of values.")
## Interpretation: I noticed that the value hovers around 2.7 which is quite similar to the number e. Every iteration is different due to the random choice of values.

Question 6. For our specific random variable, we know that its PDF is defined by the function \(f(x) = 10x(1-x)\). Utilize the accept-reject algorithm to draw samples from this distribution. Take a look at Lecture 10 slide 8 and 9

#Answer
#TAKEN FROM SLIDES ON CANVAS**********
accept_reject <- function(f,c,g,rg,n)
{
  n.accepts <- 0
  result.sample <- rep(NA, n)
  while(n.accepts < n)
  {
    x.star <- rg(1)
    u <- runif(1,0,1)
    
    if(u < f(x.star)/(c*g(x.star)))
    {
      n.accepts <- n.accepts + 1
      result.sample[n.accepts] = x.star
    }
  }
  result.sample
}

f <- function(x)
{
  10*x*(1-x)
}
g <- function(x)
{
  x/x
}
rg <- function(n)
{
  runif(n,0,1)
}
c <- 2
vals <- accept_reject(f,c,g,rg,10000)
hist(vals,breaks = 30, freq = FALSE, main = "Sample vs True Density")
xs <- seq(0,1, len = 1000)
lines(xs, dbeta(xs,2,2), col = "blue", lwd = 2)

Quesion 1 (b)

#Answer