I'm trying to use NMaximize
to show that entropy is maximized when the distribution is uniform. It seems to work when the random variable is valued, but breaks at 4+ variables:
p = {p1, p2, p3, p4};
c = Map[0 <= # <= 1 &, p];
NMaximize[{Sum[-Log[p[[i]]]*p[[i]], {i, 1, Length[p]}], Total[p] == 1,
Splice[c]}, p]
If p
is changed to {p1, p2, p3}
, then the result is p1 = p2 = p3 = 1/3
as expected. But for 4 probabilities, I get the following:
{1.30778, {p1 -> 0.3323, p2 -> 0.269063, p3 -> 0.0975481,
p4 -> 0.301089}}
Which seems clearly wrong. Am I using NMaximize
incorrectly?
Abs[p1] + Abs[p2] + Abs[p3] + Abs[p4]
by doing -NMaximize[{Total[-# Log[#] & /@ p], Splice[c], Norm[p, 1] == 1}, p]
and gives the result:{1.38629, {p1 -> 0.250001, p2 -> 0.25, p3 -> 0.25, p4 -> 0.25}}
but note the slight error of .000001 which violates the constraint. $\endgroup$"RandomSearch"
method then it gives the right result straight away:NMaximize[{Total[-# Log[#] & /@ p], Splice[c], Total[p] == 1}, p, Method -> "RandomSearch"]
$\endgroup$NMaximize[{Sum[-Log[p[[i]]]*p[[i]], {i, 1, Length[p]}], Total[p] == 1, p1 == p2 == p3 == p4, c} // Flatten, p]
. This works also with MaximizeMaximize[{Sum[-Log[p[[i]]]*p[[i]], {i, 1, Length[p]}], Total[p] == 1, p1 == p2 == p3 == p4, c} // Flatten,
yields{Log[4], {p1 -> 1/4, p2 -> 1/4, p3 -> 1/4, p4 -> 1/4}}
$\endgroup$