edited by
675 views
1 votes
1 votes

in C language rand() returns a random integer number.  Following is a function definition.

int f() {
     return (rand() & 1) ? 1:0;
}

Then what will be the expected value of count ?


 count = 0;
 for(i=1;i<=n;i++) {
    if(f() && f()) {
       count++;
    }
 }

& is bitwise AND

&& is logical AND

and assume required seed has been initialized.

edited by

1 Answer

Best answer
7 votes
7 votes
The function $f()$ is checking if the random integer generated by $rand()$ is odd. The expression $n&1$ is used for checking the parity of $n$ (odd or even), so $f()$ returns $1$ if the random number is odd and return $0$ otherwise.

Now inside the for loop, the variable $count$ is incremented only if both the $f()$'s inside the if condition are true. This happens when $2$ odd random numbers are generated.

For calculating the expected value of $count$, let us have an indicator random variable $X_i$, such that $X_i = 1$ if $count$ is incremented at the $ith$ iteration in the loop and $X_i = 0$ otherwise. Then $E[Xi] = P(Xi) = 1/4$ (Odd Even, Even Odd, Odd Odd, Even Even There are 4 possibilities. Favorable case is Odd Odd) The expected value of $count$ call this $E[Z]$ is given by $E[Z] = E[X1] + E[X2] + E[X3] + ... + E[XN]$. So $E[Z] = N * 1/4 = N/4$
selected by

Related questions

0 votes
0 votes
1 answer
1
dd asked Sep 27, 2016
1,005 views
If n balls are randomly selected from an urn containing N balls of which m are white,find the expected number of white balls selected.
2 votes
2 votes
1 answer
2
Sahil Gupta asked Nov 25, 2014
2,072 views
What is expected value of the sum of the numbers appearing on two fair dice when they are rolled given that the sum of these numbers is at least nine. That is, what is E(...