8

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]};
Print["grad f = ", gradf]
output = grad f = {2 x,2 y}
Print["grad g = ", gradg]
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.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Stan Ricky
  • 81
  • 3
  • 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. – bbgodfrey Jul 02 '15 at 01:51
  • 1
    Similar: http://mathematica.stackexchange.com/q/78400, http://mathematica.stackexchange.com/q/63351, http://mathematica.stackexchange.com/q/36847 – Michael E2 Jul 02 '15 at 03: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. – Michael Seifert Jul 02 '15 at 17:40

1 Answers1

16

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}]]

Mathematica graphics


Edit

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

Solve[{gradf == λ gradg, g[x, y] == 0}, {x, y, λ}, Reals] // N
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453