Skip to content

Instantly share code, notes, and snippets.

@tejashah88
Last active October 30, 2019 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tejashah88/7b880c596a8bcaebd3cdff5026283208 to your computer and use it in GitHub Desktop.
Save tejashah88/7b880c596a8bcaebd3cdff5026283208 to your computer and use it in GitHub Desktop.
A min/max finder based on Lagrange Multipliers with one constraint
from sympy import *
from sympy.abc import x, y, z, l
f = x**2 + y**2 + z**2
g = x**4 + y**4 + z**4
k = 9
grad = lambda fn: Matrix([fn.diff(x), fn.diff(y), fn.diff(z)]).transpose()
# grad(f) = lambda * grad(g)
first = [*(grad(f) - grad(g) * l)]
second = g - k
solns = solve([*first, second], (x, y, z, l))
final_solns = []
for soln in solns:
# filter out solutions with imaginary parts
if not (soln[0].is_imaginary or soln[1].is_imaginary or soln[2].is_imaginary or soln[3].is_imaginary):
final_solns += [soln]
vals = [f.subs({'x': x[0], 'y': x[1], 'z': x[2] }) for x in final_solns]
print('max value: ', max(vals))
print('min value: ', min(vals))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment