A possible typo in the program of "Mathematica Navigator" by Heikki
- To: mathgroup at smc.vnet.net
- Subject: [mg122114] A possible typo in the program of "Mathematica Navigator" by Heikki
- From: Nabeel Butt <nabeel.butt at gmail.com>
- Date: Sat, 15 Oct 2011 06:02:16 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
Dear All, In the chapter on 'optimization' the book presents a program to implement Kuhn Tucker conditions.I have indicated where the book appears to make the typo in the code I show below : kktOptimize[f_, g_List, h_List, x_List, \[Epsilon]_: 10.^-12] := Module[{\[Lambda]\[Lambda] = Array[\[Lambda], Length[g]], \[Mu]\[Mu] = Array[\[Mu], Length[h]], x\[Lambda]\[Mu], eqns, sol, realsol, nrealsol, ineqs, pos, cand}, x\[Lambda]\[Mu] = Join[x, \[Lambda]\[Lambda], \[Mu]\[Mu]]; eqns = Thread[ Join[D[f + \[Lambda]\[Lambda].g + \[Mu]\[Mu].h, {x}], g, \[Mu]\[Mu] h] == 0]; sol = Union[Solve[eqns, x\[Lambda]\[Mu]]]; realsol = Select[sol, FreeQ[Chop[N[#], \[Epsilon]], Complex] &]; If[realsol == {}, Return["No real solutions; try a larger \[Epsilon]"]]; nrealsol = Thread[x\[Lambda]\[Mu] -> #] & /@ Chop[N[x\[Lambda]\[Mu] /. realsol], \[Epsilon]]; (*Here below this line the book makes a typo and I have made the appropriate correction -instead of just h<=epsilon it also joined the mu vector *) ineqs = Thread[h <= \[Epsilon]]; pos = Position[(And @@ #) & /@ (ineqs /. nrealsol), True]; If[pos == {}, Return["Inequalities not satisfied; try a larger \[Epsilon]"]]; cand = Union[Sort /@ Extract[realsol, pos]]; First[Sort[Transpose[{f /. cand, cand}], #1[[1]] < #2[[1]] &]]] Now the above program works fine after I have made the correction.For example you can run : f = -((x - 2)^(1.5) + (y - 3)^2); h1 = x + y - 9; h2 = 2 - x; h3 = 3 - y; kktOptimize[f, {}, {h1, h2, h3}, {x, y}] OR if you are too eager : f = -((Log /@ x - 2)^(1.5) + (y - 3)^2); h1 = x + y - 9; h2 = 2 - x; h3 = 3 - y; kktOptimize[f, {}, {h1, h2, h3}, {x, y}] Work fines now.Perhaps you guys already know but it is good to point out errors so that they could be corrected in the next edition !. It is also possible I am wrong so nice to know if I am making errors ! Thanks... Nabeel <http://t2.gstatic.com/images?q=tbn:ANd9GcRd4WJa3qO12skxxSAppQ9HimoQsMP5o--uCIe7yxZahJqlkN4z> "We have not succeeded in answering all our problems.The answers we have found only serve to raise a whole set of new questions.In some ways we feel that we are as confused as ever,but we believe we are confused on a higher level and about more important things." "Maybe one day we get to see all the beauty present in this world" "Life can only be understood going backwards but it must be lived going forwards" Nabeel Butt UWO,London Ontario, Canada