Lagrange Multipliers

4431 days ago by pub

var('x y t l') f(x, y) = x^2 + 2 * y^2 g(x, y) = x^2 + y^2 
       
def gradient(f, X): return vector([ diff(f, x) for x in X]) 
       
S = solve([diff(f(x, y), x) == l * diff(g(x, y), x), diff(f(x, y), y) == l * diff(g(x, y), y), g(x, y) == 1], [x, y, l], solution_dict = True) S 
       
[{y: 0, x: 1, l: 1}, {y: 0, x: -1, l: 1}, {y: -1, x: 0, l: 2}, {y: 1, x:
0, l: 2}]
[{y: 0, x: 1, l: 1}, {y: 0, x: -1, l: 1}, {y: -1, x: 0, l: 2}, {y: 1, x: 0, l: 2}]
P = contour_plot(f(x, y), (x, -2.5, 2.5), (y, -1.5, 1.5), contours = srange(0, 3.01, 0.5), plot_points = 1000, fill = False) P += parametric_plot([cos(t), sin(t)], 0, 2 * pi, color = 'red') for s in S: p = vector([x, y])(s) P += arrow(p, p + gradient(f(x, y), [x, y])(s), rgbcolor = 'black') P += arrow(p, p + gradient(g(x, y), [x, y])(s), rgbcolor = 'red') P += point(p, pointsize = 30) show(P) 
       
P = plot3d(f(x, y), (x, -1.5, 1.5), (y, -1.5, 1.5)) P += parametric_plot3d([cos(t), sin(t), 0], (t, 0, 2 * pi), thickness = 2, color = 'red') P += parametric_plot3d([cos(t), sin(t), f(cos(t), sin(t))], (t, 0, 2 * pi), thickness = 2, color = 'green') for s in S: p = [x(s), y(s), f(x(s), y(s))] P += point3d(p, size = 10, color = 'black') show(P) 
       
var('u v') P = parametric_plot3d([u * cos(v), u * sin(v), f(u * cos(v), u * sin(v))], (u, 0, 1), (v, 0, 2 * pi)) P += parametric_plot3d([cos(t), sin(t), 0], (t, 0, 2 * pi), thickness = 2, color = 'red') P += parametric_plot3d([cos(t), sin(t), f(cos(t), sin(t))], (t, 0, 2 * pi), thickness = 2, color = 'green') for s in S: p = [x(s), y(s), f(x(s), y(s))] P += point3d(p, size = 10, color = 'black') show(P)