Discrete uniform moments on an integer interval (source code)

= Discrete uniform moments on an integer interval
{title2=$\mathbb E X=(a+b)/2,\quad\operatorname{Var}(X)=(n^2-1)/12$}

Suppose the <support of a probability distribution> consists of all consecutive <integers> from $a$ to $b$, including both endpoints, with $a\leq b$. Its <cardinality> is $n=b-a+1$, and a <discrete uniform distribution> on it satisfies
$$
\mathbb E X=\frac{a+b}{2},\qquad
\operatorname{Var}(X)=\frac{n^2-1}{12}=\frac{(b-a)(b-a+2)}{12}.
$$
For a short derivation, set $K=X-a$, whose possible values are $0,\ldots,n-1$. The finite <sums> give
$$
\sum_{k=0}^{n-1}k=\frac{n(n-1)}2,\qquad
\sum_{k=0}^{n-1}k^2=\frac{n(n-1)(2n-1)}6,
$$
and hence
$$
\mathbb E K=\frac{n-1}{2},\qquad
\mathbb E[K^2]=\frac{(n-1)(2n-1)}6,\qquad
\operatorname{Var}(K)=\frac{(n-1)(2n-1)}6-\frac{(n-1)^2}{4}=\frac{n^2-1}{12}.
$$
Adding $a$ shifts the <expected value> by $a$ and leaves the <variance> unchanged. For completeness, the first <sum> follows by pairing $k$ with $n-1-k$. For the second, sum $(k+1)^3-k^3=3k^2+3k+1$ from $k=0$ to $n-1$: the left side is $n^3$, so inserting the first <sum> gives the stated result.

The edge case $a=b$ has $n=1$: $X=a$ with <probability> one, <expected value> $a$, and <variance> zero. On an <arithmetic progression> $\{a,a+h,\ldots,a+(n-1)h\}$ with $h>0$, the same argument instead gives <expected value> $a+h(n-1)/2$ and <variance> $h^2(n^2-1)/12$. Equal spacing is the extra hypothesis behind these formulas; the <discrete uniform distribution> on $\{1,2,4,8\}$ requires the general <sums> above.