
####################################################
#   Function definitions for Chapter 5


################################################
# Function to illustrate random number generation
# by LCGs
LCG <- function(a,c,m,seed,N){
  ZSeq <- numeric(N)
  USeq <- numeric(N)
  for (i in 1:N){
    # the operator %% implements mod
    seed <- (a*seed+c) %% m 
    ZSeq[i] <- seed
    USeq[i] <- seed/m
  }
  return(list(U=USeq, Z=ZSeq))
}


################################################
# Function to sample from an empirical discrete
# distribution by inverse transformation 
EmpiricalDrnd <- function(values, probs, howmany){
  # make sure probs add up to 1
  probs <- probs/sum(probs)
  # get cumulative probabilities
  cumprobs <- cumsum(probs)
  N <- length(probs)
  sample <- numeric(howmany)
  for (k in 1:howmany){
    loc <- sum(runif(1)>cumprobs)+1
    sample[k] <- values[loc]
  }
  return(sample)
}


################################################
# Function to sample a multivariate normal
MultiNormrnd <- function(mu,sigma,howmany){
  n <- length(mu)
  Z <- matrix(0,nrow=howmany,ncol=n)
  U <- chol(sigma)
  for (i in 1:howmany)
    Z[i,] <- mu + rnorm(n) %*% U
  return(Z)
}
