Skip to content
Advertisement

Conditional expressions in sagemath, when defining a symbolic expression

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement