# Need help with the Lagrange multiplier method

Well I am new to Mathematica and got really stuck solving this problem.

In class, I was ask to use the Lagrange multiplier method to find the maximum and minimum value of $f(x,y) = x^2+y^2$ which lies on the curve $x^4 + 4xy + 2y^4 = 8$

What I did was

F[x_, y_] := x^2 + y^2
G[x_, y_] := x^4 + 4 x y + 2 y^4 - 8
gradf = {D[F[x, y], x], D[F[x, y], y]};
gradg = {D[G[x, y], x], D[G[x, y], y]};
output = grad f = {2 x,2 y}
output = grad g = {4 x^3+4 y,4 x+8 y^3}
Solve[{gradf[x, y] == lambda gradg[x, y], g[x, y] == 8}, {x, y, lambda}]


Then after this part I keep getting an error message or some ridiculous infinite number.

• Welcome to Mathematica.SE! I hope you will become a regular contributor. To get started, 1) take the introductory Tour now, 2) when you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge, 3) remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign, and 4) give help too, by answering questions in your areas of expertise. Jul 2 '15 at 1:51
• Jul 2 '15 at 3:18
• @belisaurius's solution below is a good one, but just to make explicit the errors in your above code: (1) gradf and gradf[x, y] are not the same thing as far as Mathematica is concerned (you use these inconsistently); (2) G[x, y] and g[x, y] are not interchangeable (you define the former and then use the latter in Solve); (3) it's generally best practice to avoid defining capitalized variables, as they can't conflict with Mathematica's own predefined functions; (4) your output statements don't actually do anything. Jul 2 '15 at 17:40

The "canonical" way in Mathematica is

f[x_, y_] := x^2 + y^2
g[x_, y_] := x^4 + 4 x y + 2 y^4 - 8
Maximize[{f[x, y], g[x, y] == 0}, {x, y}]


If you want to make explicit usage of the Lagrange multiplier:

ss = N@Solve[Grad[f[x, y] + λ g[x, y], {x, y}] == 0 && g[x, y] == 0, {x, y, λ}, Reals]


gives the {x, y} coordinates of the maxs and mins.

Show[
ContourPlot[f[x, y],      {x, -3, 3}, {y, -3, 3}, ColorFunction -> "Pastel",
Epilog -> {Red, PointSize[Large], Point[{x, y} /. ss]}],
ContourPlot[g[x, y] == 0, {x, -3, 3}, {y, -3, 3}, ContourStyle -> {Thick, Green}]] Edit

If you want to keep your own grad definitions you could write:

Solve[{gradf == λ gradg, g[x, y] == 0}, {x, y, λ}, Reals] // N

• bel, why not just use the third argument of Solve[] to throw out the complex solutions? Jul 2 '15 at 3:37
• @J.M. Didn't work when I tried it first. Tried again after reading your comment and the obvious conclusion is that I made a mistake the first time. :) Jul 2 '15 at 3:41
• nice and elegant; did not know about the third argument of Solve. Jul 2 '15 at 6:52
• …and if you're still stuck in a version without Grad[]: D[f, {{x, y}}]. Jul 2 '15 at 14:55