How do I expand a sum?

Distribute @ Sum[-2 Subscript[x, i] (-a Subscript[x, i] - b + Subscript[y, i]) // Expand,
                 {i, n}] == 0

enter image description here


I had this question also a few times, but I never bothered to solve it properly. Here is my solution, which also moves constant factors out of the sums:

SumExpand[exp_] := exp /. Sum[c_, {i_, a_, b_}] :> Distribute[Sum[ExpandAll[c], {i, a, b}]]
SumSimplify[exp_] := SumExpand[exp] /. Sum[c_, {i_, a_, b_}] :> Apply[Times, Extract[c, Position[D[c /. Times -> List, i], 0]]] Sum[c/Apply[Times, Extract[c, Position[D[c /. Times -> List, i], 0]]], {i, a, b}]

Here is an example (linear regression):

err = Sum[(c0 + c1 x[i] - y[i])^2, {i, 1, n}]
gl1 = D[err, c0] // SumSimplify
gl2 = D[err, c1] // SumSimplify

The results are: $$err = \sum\limits_{i=1}^n (c_0 + c_1 x[i] - y[i])^2$$ $$gl1 = 2 c_0 n + 2 c_1 \sum\limits_{i=1}^n x[i] - 2 \sum\limits_{i=1}^n y[i]$$ $$gl2 = 2 c_0 \sum\limits_{i=1}^n x[i] + 2 c_1 \sum\limits_{i=1}^n x[i]^2 - 2 \sum\limits_{i=1}^n x[i] y[i]$$

The code

Solve[{gl1 == 0, gl2 == 0}, {c0, c1}]

gives the parameters $c_0$ and $c_1$.