# defining a function

if I define

f = e^(-x-y)


then

var('a,b')
f(a,b)


returns e^(-a-b)

f(1,1)


returns e^(-2)

But I want the real value. So here is my question, how to define a function (with the SageMath protocol or the def of Python such that if the arguments are variables it return the symbolic function with the symbolic variables and if the arguments are, say, explicit real value numbers? There is one more problem when the argument are of the type (1,a).

There is a begining of answer in the asksagemath question "How to define Sage function with Optional arguments?" but in that case I do not know how to condition on say real or symbolic arguments.

edit retag close merge delete

Sort by ยป oldest newest most voted

Since your expression can be numerically evaluated only if all arguments are numeric, you can try :

sage: def foo(x, y): return e^(-x-y).n() if all(map(lambda u:SR(u).is_numeric(), (x, y))) else e^(-x-y)
sage: foo(a,b)
e^(-a - b)
sage: foo(1,1)
0.135335283236613
sage: foo(1,a)
e^(-a - 1)
sage: foo(x,1)
e^(-x - 1)


Alternative :

sage: def foo(x, y):
....:     r=e^(-x-y)
....:     try:
....:         return r.n()
....:     except:
....:         return r
....:
sage: foo(a, b)
e^(-a - b)
sage: foo(a, 1)
e^(-a - 1)
sage: foo(1, 1)
0.135335283236613


HTH,

more