TITLE: Variance of number of runs of consecutive heads in $n$ biased coin flips
QUESTION [8 upvotes]: Suppose we have a sequence of $n$ coin flips of a biased coin with probability $p$ of being heads. Let $X_n$ be the random variable that records the number of runs of consecutive heads, e.g. THHTHTHH has 3 runs of heads. By linearity of expectation, $E(X_n)$ is the sum of $n$ probabilities of getting a run of heads starting at coin flip $j$ for $1 \leq j \leq n$. For $j = 1$ this probability is $p$, and for $j > 1$ we must have flip $j-1$ is tails and flip $j$ is heads, which has probability $p(1-p)$. So $E(X_n) = p + (n-1)p(1-p)$. What about Var$(X_n)$? Is there any way to compute a formula for it? Or if not, at least get asymptotics for it?

REPLY [2 votes]: We seem to have two different results for the variance. To investigate this I wrote some Maple code to compute $[z^n] G(z,u)$ by direct enumeration. As far as what I posted earlier the direct generating function seems to match the algebraic one and the same goes for expectation and variance.
Here is $[z^3] G(z, u)$
$$ \left( 1-p \right) ^{3}+3\,p \left( 1-p \right) ^{2}u+2\,{p}^{2} \left( 1-p \right) u+{p}^{2} \left( 1-p \right) {u}^{2}+{p}^{3}u $$
and this is $[z^4] G(z, u)$
$$  \left( 1-p \right) ^{4}+4\, \left( 1-p \right) ^{3}pu+3\,{p}^{2} \left( 1-p \right) ^{2}u+3\,{p}^{2} \left( 1
-p \right) ^{2}{u}^{2}\\+2\,{p}^{3} \left( 1-p \right) u+2\,{p}^{3} \left( 1-p \right) {u}^{2}+{p}^{4}u.$$
These two generating functions can be verified with pen and paper. To conclude, here is how I computed them. The two functions mom_ex and mom_var compute the moments i.e. expectation and variance. Note that $[z^{11}] G(z,u)$ has only $37$ terms, so this calculation is quite reasonable.


ev :=
proc(n)
    option remember;
    local q, d, pos, pb, pf, r, gf;


    gf := 0;

        for q from 2^n to 2^(n+1)-1 do
            d := convert(q, base, 2);

            if d[1] = 1 then
                r := 1;
                pf := p;
                pb := p;
            else
                r := 0;
                pf := 1-p;
                pb := 1-p;
            fi;

            for pos to n-1 do
                if d[pos] <> d[pos+1] then
                    if d[pos+1] = 1 then r := r+1; fi;
                    pf := 1-pf;
                fi;
                pb := pb*pf;
            od;

            gf := gf+pb*u^r;
        od;

    gf;
end;

mom_ex :=
proc(n)
        expand(subs(u=1, diff(ev(n), u)));
end;

mom_var :=
proc(n)

        expand(subs(u=1, diff(ev(n), u$2)))
        + mom_ex(n)-mom_ex(n)^2;
end;