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

Sort by ยป oldest newest most voted

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 ?

more

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

( 2020-10-14 20:07:50 +0200 )edit

I turned @Emmanuel Charpentier's comment into an answer so you can accept it and thus mark the question as solved.

( 2021-01-01 21:49:10 +0200 )edit