I was implementing a simple scheme of Bernoulli distribution sampler. $ X sim B(p) $.

I have a function that generates a uniform random number $r in (0,1)$. Then, I set $ X = 1 $ if $p > r $, and $X =0$ otherwise. Is this correct?

**Contents**hide

#### Best Answer

If $X$ is a Bernoulli random variable then $E[X]=p$ and $V[X]=p(1-p)$. For example:

`> x <- rbinom(1000,1,0.3) > mean(x) [1] 0.302 > var(x) [1] 0.211007 `

The most basic way to generate a Bernoulli sample is (Kachitvichyanukul and Schmeise): $$begin{align} 1.&quad x leftarrow 0, k leftarrow 0 \ 2.&quad text{Repeat} \ &quadquad text{Generate } usimmathcal{U}(0,1), kleftarrow k + 1 \ &quadquad text{if }ule ptext{ then } x leftarrow x + 1\ &quadtext{Until }k = n \ 3.&text{Return}end{align}$$ This algorithm generates $x$ successes out of $n$ trials, but can be slightly modified to generate a sample form the Bernoulli distribution. In R:

`> 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(1000, 0.3) > mean(x) [1] 0.314 > var(x) [1] 0.2156196 `

### Similar Posts:

- Solved – Difference of two independent gamma distribution
- Solved – Sum of Bernoulli random variables with Gaussian noise
- Solved – Conditional Logistic Regression in R
- Solved – Find the sampling distribution of the MLE of the uniform distribution
- Solved – Given Bernoulli probability, how to draw a Bernoulli from a uniform distribution