0
$\begingroup$

I want to minimize a function involving the sum of $n$ fixed (but indetermined) $x$ values, for example:

Minimize[Sum[(x[i] - a)^2, {i, 1, n}], a]

Expected answer: Sum[x[i], {i, 1, n}]/n

Is there a way to represent this sum and solve the problem symbolically?

$\endgroup$
3
  • $\begingroup$ By "known but undetermined", do you mean that they do not actually have explicit values, but are merely formal signifiers? $\endgroup$
    – thorimur
    Oct 29 '20 at 14:03
  • $\begingroup$ @thorimus Exactly! $\endgroup$
    – WHoZ
    Oct 29 '20 at 14:10
  • 1
    $\begingroup$ Works fine if you set $n$ to a specific value. $\endgroup$
    – Roman
    Oct 29 '20 at 14:37
3
$\begingroup$

Here a solution without specifying n. Following the approach here https://mathematica.stackexchange.com/a/16972 to distributes the terms in the sum you could compute the extremum explicitly

Sum[(x[i]-a)^2,{i,1,n}]
Distribute@D[%,a]
Solve[%==0,a]

which gets you a candidate for an extremum at

a -> -Sum[-2*x[i], {i, 1, n}]/(2*n)

which is in fact a minimum since the second derivative

Sum[(x[i] - a)^2, {i, 1, n}]
Distribute@D[%, a, a]

is positive (2n) for all a. I do not know how one could get Minimize to work without specifying n.

$\endgroup$
1
$\begingroup$

Works fine for me:

n = 4;
Minimize[Sum[(x[i] - a)^2, {i, 1, n}], a]

(*    {1/4 (3 x[1]^2 - 2 x[1] x[2] + 3 x[2]^2 - 2 x[1] x[3] - 2 x[2] x[3] + 3 x[3]^2 - 2 x[1] x[4] - 2 x[2] x[4] - 2 x[3] x[4] + 3 x[4]^2),
      {a -> 1/4 (x[1] + x[2] + x[3] + x[4])}}    *)

and

D[Sum[(x[i] - a)^2, {i, 1, n}], a] /. a -> Sum[x[i], {i, 1, n}]/n // Expand

(*    0    *)
$\endgroup$
1
  • $\begingroup$ Oh, that's great! I didn't think of trying to set a specific value for n. Thanks! $\endgroup$
    – WHoZ
    Oct 29 '20 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.