Ask Your Question

Evaluation of logical compound expressions

asked 2020-07-15 23:38:13 +0200

Emmanuel Charpentier gravatar image
sage: foo=sin(x) > 0 ; foo
sin(x) > 0
sage: bar=cos(x)>0 ; bar
cos(x) > 0

I do not understand this :

sage: foo and bar
sin(x) > 0
sage: foo or bar
cos(x) > 0

As long as x has no value, these expressions can't be evaluated or simplified. Could some kind soul enlighten my confused mind ?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2020-07-16 00:04:24 +0200

jaydfox gravatar image

updated 2020-07-16 00:10:49 +0200

From my testing, it appears that foo is evaluating to False. Hence, in the expression "foo and bar", the foo is evaluating as False, so it skips evaluation of bar. As such, it is returning the first operand, foo, which is sin(x) > 0.

In the second expression, "foo or bar", the foo evaluates as False. With an "or" operator, the second operand must be evaluated. As such, it's returning the second operand, bar, cos(x) > 0.

You can see similar behavior of the "and" and "or" operators with the following:

sage: 0.0 and sin(x)
sage: 0.0 or sin(x)

Edit: Sorry, this probably didn't answer the original question. I can't tell you why foo is being evaluated as False, given the unknown value of x. However, I can reasonably assume that foo is being evaluated as False. If you plug in a value for x, like foo(2.0), then it correctly evaluates as True.

edit flag offensive delete link more

answered 2020-07-16 09:44:23 +0200

Emmanuel Charpentier gravatar image

Okay. As jaydfox points out, there are three things :

  • and evaluates "lazily" from left to right, and stops at the first argument evaluated to False.

  • Anything that can't be proven True evaluates to False.

  • and returns the first False argument unevaluated.

The last one baffles me. it means that I can't write if sin(x>0 and cos(x>0): doSomething(): I would doSomething() if x was unbound....

I need to write if (sin(x)>0 and cos(x)>0) is True: doSomething().

edit flag offensive delete link more


Hmm, I checked that last one. Here's what I'm seeing:

sage: if (sin(x)>0 and cos(x)>0): print("Hello!")
sage: if (sin(x)>0 or cos(x)>0): print("Hello!")
sage: if not (sin(x)>0 and cos(x)>0): print("Hello!")
jaydfox gravatar imagejaydfox ( 2020-07-17 22:55:31 +0200 )edit

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


Asked: 2020-07-15 23:38:13 +0200

Seen: 243 times

Last updated: Jul 16 '20