Ask Your Question
1

defining a function

asked 2023-01-18 12:33:59 +0200

Cyrille gravatar image

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

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-01-18 14:01:49 +0200

Emmanuel Charpentier gravatar image

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,

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-01-18 12:33:59 +0200

Seen: 163 times

Last updated: Jan 18 '23