Given pmf of $X$, how $P(X\text{ is even})$ using R?

184 Views Asked by At

I have a pmf of $X$, which is $X\sim \text{Bin}(n=20, p=0.2)$. I want to figure out how to calculate using R $P(X \text{ is even})$. This is what I figured out, by hand you would basically sum all even of $X$. Is the only way in R to do this is by summing dbinom(x=i,size=20,prob=0.2) where is i is an even number in range(0,20)? There must be a clever way?

4

There are 4 best solutions below

5
On BEST ANSWER
> i = seq(0, 20, by = 2)
> sum(dbinom(i, 20, .2))
[1] 0.5000183

You might want to look at the documentation, ?seq.


You could also do

> sum(dbinom(2*(0:10), 20, .2))
[1] 0.5000183
0
On

you could use a vector calculation such as , even<- seq(2,20,by=2); sum(dbinom(x=even, size=20, prob=0.2)); R is working best for vector type calculation. In this way you can avoid by adding 10 times individually. Hope this help.

1
On

For the sake of completeness (as this is a mathematics site and not a programming site), given $X \sim \operatorname{Binomial}(n,p)$, let $E$ represent the event that $X$ is even. Then $$\Pr[E] = \sum_{x=0}^{\lfloor n/2\rfloor} \binom{n}{2x} p^{2x} (1-p)^{n-2x}.$$ To evaluate this sum, it is helpful to recall that $$(a+b)^n = \sum_{x=0}^n \binom{n}{x} a^{n-x} b^x,$$ so that $$(a+b)^n + (a-b)^n = \sum_{x=0}^n \binom{n}{x} (a^{n-x} b^x + a^{n-x} (-b)^x) = \sum_{x=0}^n \binom{n}{x} a^{n-x} b^x (1 + (-1)^x).$$ But notice that the expression $$1 + (-1)^x = \begin{cases} 2, & x \text{ is even} \\ 0, & x \text{ is odd}. \end{cases}$$ So it follows that $$(a+b)^n + (a-b)^n = 2 \sum_{x=0}^{\lfloor n/2\rfloor} \binom{n}{2x} a^{n-2x} b^{2x},$$ and the choice $a = 1-p$, $b = p$ gives $$\Pr[E] = \frac{1}{2}(((1-p)+p)^n + ((1-p)-p)^n) = \frac{1 + (1-2p)^n}{2},$$ for $p \in [0,1].$


As for the specific case provided in the question, $n = 20$ and $p = 1/5$, the exact probability should be $$\frac{47685459212513}{95367431640625} = 0.50001828079220031488.$$

0
On

If the probability that you have an even number of successes after $n$ attempts is $e_n$ then $e_0=1$ and $$e_n=(1-p) e_{n-1} + p(1-e_{n-1})$$ which you can rewrite as $e_n=(1-2p) e_{n-1} + p$ and $e_n-\frac12 = (1-2p) (e_{n-1}-\frac12)$ giving a general result of $$e_n=\frac12+ \frac12(1-2p)^n$$ which when $n=20$ and $p=0.2$ gives $e_{20} = 0.5+0.5\times 0.6^{20} \approx 0.500018281$