0
$\begingroup$

I'm trying to use NMinimize to solve a puzzle. Some of the code is below...

sumCoords = {{1, 2, 3}, {1, 5, 10, 15, 19}, {1, 4, 8}, {2, 5, 9, 
    13}, {2, 6, 11, 16}, {3, 7, 12}, {3, 6, 10, 14, 17}, {4, 5, 6, 
    7}, {4, 9, 14, 18}, {7, 11, 15, 18}, {8, 9, 10, 11, 12}, {8, 13, 
    17}, {12, 16, 19}, {13, 14, 15, 16}, {17, 18, 19}};
f[v_] := Total[Map[(Total[v[[#]]] - 38)^2 &, sumCoords]] + 
  10 (CountDistinct[v] - 19)^2
trueMin = {15, 13, 10, 14, 8, 4, 12, 9, 6, 5, 2, 16, 11, 1, 7, 19, 18,
    17, 3};
(* Check that the f = 0 at the known solution to the puzzle *)
f[trueMin];

params = Table[Subscript[x, i], {i, 1, 19}];
rangeConstraint = Map[1 <= # <= 19 &, params];

steps = {};
Dynamic[ListLogPlot[steps, PlotRange -> All, Joined -> True]]
sol = NMinimize[{
   f[params],
   rangeConstraint, params ∈ Integers}, params, 
  MaxIterations -> 200, StepMonitor :> AppendTo[steps, f[params]], 
  Method -> {"NelderMead"}]

sol[[1]]
f[params /. sol[[2]]]

The output I get is

15.
505

NMinimize returns {min, params} but why don't the parameters evaluate to the minimum. In other words, shouldn't the output lines be equal even if that is nowhere near the actual minimum?

$\endgroup$
0
$\begingroup$
f[params/.sol[[2]]]

does exactly what you are telling it to. Because:

params/.sol[[2]]

gives you {13, 14, 10, 16, 1, 5, 17, 8, 11, 3, 6, 10, 13, 2, 8, 14, 16, 8, 14}.

What you want is:

f[params]/.sol[[2]] 
$\endgroup$

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.