Demo entry 6760748

Lagrange Multiplier

   

Submitted by anonymous on Sep 18, 2018 at 05:45
Language: Python 3. Code size: 840 Bytes.

import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize as opt

def f(x):
    return (10 - x[0]**2 - x[1]**2)

x = np.linspace(-3, 3, 200)
y = np.linspace(-3, 3, 200)
X, Y = np.meshgrid(x, y)
Z = f(np.vstack([X.ravel(), Y.ravel()])).reshape((200,200))
plt.contour(X, Y, Z, np.arange(-2.0,10, 1), cmap='jet')
plt.plot(x, x**2, 'k:', linewidth=1,label="non-equality")
plt.plot(x, -x, 'k--', linewidth=1, label="equality")
plt.xlabel('x1')
plt.ylabel('x2')
plt.axis([-3,3,-3,3])
plt.legend()
plt.colorbar()
plt.show()

cons = ({'type': 'eq',
         'fun' : lambda x: np.array([x[0] + x[1]]),
         'jac' : lambda x: np.array([1.0, 1.0])},
        {'type': 'ineq',
         'fun' : lambda x: np.array([x[1] - x[0]**2])})

x0 = [0, 1.0]
cx = opt.minimize(f, x0, constraints=cons)
print(cx)

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).