# Discrete Random Variables

Here's my R-code for an inversion sampler to generate a sample of 1000 random numbers from the distribution of X. Use the generated CNRG pseudo-random numbers (do not use any functions, which directly implement the sampler like rbinom()).

``````discrete.inv.transform.sample <- function( p.vec ) {
Xo<-2
a<-3
c<-5
m<-1000
X <- numeric(length = m)
X<-Xo
for(i in 2:m){
X[i] <- (a*X[i-1]+c)%%m
}
U <- X/m

if(U <= p.vec){
return(1)
}
for(state in 2:length(p.vec)) {
if(sum(p.vec[1:(state-1)]) < U && U <= sum(p.vec[1:state]) ) {
return(state)
}
}
}
``````

I need to Show the probability mass function of the sample of simulated random numbers. Include the true probability mass function in the plot for a comparison.

``````num.samples <- 1000
p.vec        <- c(0.1, 0.2, 0.4, 0.1,0.2)
names(p.vec) <- 1:5
samples     <- numeric(length=num.samples)
for(i in seq_len(num.samples) ) {
samples[i] <- discrete.inv.transform.sample(p.vec)
}
barplot(p.vec, main='True Probability Mass Function')
``````

but when I plot the empirical probability mass function, the graph only got X=1 show up,

``````barplot(table(samples), main='Empirical Probability Mass Function')
`````` can someone please tell me how to fix the problem?
thank you

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.