# Creating a function in Sage

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
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
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 close merge delete

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 ?

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
ti=[["$\\lambda$","$x$", "$y$", "$f(x, y)$"]]