Conditional expressions in sagemath, when defining a symbolic expression
Question:
In SageMath, (version 4.7), I do this in the notebook:
var("x y")
dens(x, y) = 2 if y <= x else 0
and this gives no error. However, after that,
dens(1, 1)
returns 0
,
dens(1, 0.5)
returns 0
,
- and so on!
In fact, I found no way to get the answer 2
.
What am I doing wrong?
Answers:
You’re using the Sage function declaration syntax — f(x,y) = something-or-other — but on the right hand side you’re not putting a Sage expression but a Python one. This is evaluated when it’s declared. By which I mean:
sage: var("x y")
(x, y)
sage: bool(y <= x)
False
sage: dens = 2 if y <= x else 0
sage: dens
0
sage: dens(x,y) = 2 if y <= x else 0
sage: dens
(x, y) |--> 0
If you only care about the values that the function take (say, you’re plotting it), you can simply use a Python function. If you want to differentiate it etc. you’re in for a harder go of it, I’m afraid.
piecewise
functions are often helpful:
https://doc.sagemath.org/html/en/reference/functions/sage/functions/piecewise.html
Also note the slightly different from sympy import Piecewise
which can handle symbolic conditions.
Still, I’d think that sympy (part of sage) would have symbolic "if" expressions – but can’t find anything when googling for "sympy symbolic if".
In SageMath, (version 4.7), I do this in the notebook:
var("x y")
dens(x, y) = 2 if y <= x else 0
and this gives no error. However, after that,
dens(1, 1)
returns0
,dens(1, 0.5)
returns0
,- and so on!
In fact, I found no way to get the answer 2
.
What am I doing wrong?
You’re using the Sage function declaration syntax — f(x,y) = something-or-other — but on the right hand side you’re not putting a Sage expression but a Python one. This is evaluated when it’s declared. By which I mean:
sage: var("x y")
(x, y)
sage: bool(y <= x)
False
sage: dens = 2 if y <= x else 0
sage: dens
0
sage: dens(x,y) = 2 if y <= x else 0
sage: dens
(x, y) |--> 0
If you only care about the values that the function take (say, you’re plotting it), you can simply use a Python function. If you want to differentiate it etc. you’re in for a harder go of it, I’m afraid.
piecewise
functions are often helpful:
https://doc.sagemath.org/html/en/reference/functions/sage/functions/piecewise.html
Also note the slightly different from sympy import Piecewise
which can handle symbolic conditions.
Still, I’d think that sympy (part of sage) would have symbolic "if" expressions – but can’t find anything when googling for "sympy symbolic if".