Creating a function in Sage

asked 2020-10-14 10:29:52 -0500

florin gravatar image

Hi I have a sequence of commands which does Lagrangian optimization

var('a, b, x, y, lam')
assume(a>=0,b>=0,x>= 0)
f = x*y #minimiser et maximiser sous contrainte d'egalite h=0
h = x^2/a^2 + y^2/b^2-1
L = f + h * lam
DL = L.gradient([x, y])
sol = solve([DL[k] == 0 for k in range(len(DL))]+[ h == 0],x, y, lam,
solution_dict=True)
ti=[["$\\lambda$","$x$", "$y$", "$f(x, y)$"]]
re=[(sol[j]
[lam],sol[j][x], sol[j][y],f(x=sol[j][x], y=sol[j][y])) for j in
range(4)]
table(ti + re, header_row = True)

and I would like to turn it into a function. I add the declaration, but I get no output. I know neither why, nor how to debug this. Thanks for any help :)

def optL(f,h):
       var('a, b, x, y, lam')
       assume(a>=0,b>=0,x>= 0)
       L = f + h * lam
       DL = L.gradient([x, y])
       sol = solve([DL[k] == 0 for k in range(len(DL))]+[ h == 0],x, y, lam,
       solution_dict=True)
       ti=[["$\\lambda$","$x$", "$y$", "$f(x, y)$"]]
       re=[(sol[j][lam],sol[j][x], sol[j][y],f(x=sol[j][x], y=sol[j][y])) for j in range(4)]
       table(ti + re, header_row = True)
optL(x*y,x^2/a^2 + y^2/b^2-1)
edit retag flag offensive close merge delete

Comments

Without looking at what your code does, a couple remarks :

  1. You need to return the value(s) of the function

  2. Returning atable isn't probably what you want ; what about a dictionary ?

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2020-10-14 10:57:39 -0500 )edit

Merci, Emmanuel, now it works :)

def optL(f,h):
   var('a, b, x, y, lam')
   assume(a>=0,b>=0,x>= 0)
   L = f + h * lam
   DL = L.gradient([x, y])
   sol = solve([DL[k] == 0 for k in range(len(DL))]+[ h == 0],x, y, lam,
   solution_dict=True)
   ti=[["$\\lambda$","$x$", "$y$", "$f(x, y)$"]]
   re=[(sol[j][lam],sol[j][x], sol[j][y],f(x=sol[j][x], y=sol[j][y])) for j in range(len(sol))]
   ans=table(ti + re, header_row = True)
   show(ans)
   return re
ex5=optL(x*y,x^2/a^2+ y^2/b^2-1)
ex5
florin gravatar imageflorin ( 2020-10-14 13:07:50 -0500 )edit