In: Statistics and Probability
3. Only using the runif function with default settings, generate:
(a) n = 1e4 iid realizations from a Bernoulli distribution with probability of success parameter, θ = 0.7.
(b) n = 1e4 iid realizations from a Binomial distribution with probability of success parameter, θ = 0.7 and number of trials= 20.
(c) n = 1e4 iid realizations from an Exponential distribution with mean µ = 7 (hint: if X ~ Exp(µ) then Var(X) = µ2 ).
For each case comment on the sample mean and sample variance of these realizations and if match what you expect.
(a) R-code-Generate random number 1e4 with Bernoulli distribution.
rm(list=ls())
rbernoulli <- function(n, p) {
x <- c()
for (i in 1:n) {
u <- runif(1,0,1)
if (u <= p)
x <- c(x, 1)
else
x <- c(x, 0)
}
return (x)
}
x <- rbernoulli(10000, 0.7)
mean(x)
var(x)
output-
> mean(x)
[1] 0.6941
> var(x)
[1] 0.2123464
>
(c) Generate random number 1e4 with expoential distribution.
rm(list=ls(all=T))
ls(all=T)
u=runif(1)
f<-function(u,a){
(-1/a)*log(1-u)
}
rm(list=ls(all=T))
ls(all=T)
u=runif(1)
f<-function(u,a){
(-1/a)*log(1-u)
}
x<-c(0)
u<-c(0)
for(i in 1:1000){
u[i]=runif(1)
x[i]=(-1/2)*log(1-u[i])
}
mean(x)
var(x)
output-
> mean(x)
[1] 0.5061411
> var(x)
[1] 0.2372458
>
(B)Generate random number 1e4 with Binomial distribution.
rbinomial <- function(n,size, p) {
x <- c()
for (i in 1:n) {
u <- runif(1,0,1)
if (u <= p)
x <- c(x, 1)
else
x <- c(x, 0)
}
return (x)
}
x <- rbinomial(10000,20, 0.7)
output
> mean(x)
[1] 0.7059
> var(x)
[1] 0.207626
>