Precedence of negation

52 views
Skip to first unread message

Paul Royik

unread,
Mar 24, 2021, 4:13:03 PM3/24/21
to sympy
Is there any reason why precedence of -x equals precedence of Add?
-x is (-1)*x

Aaron Meurer

unread,
Mar 24, 2021, 4:36:52 PM3/24/21
to sympy
Can you clarify what you mean by this?

The precedence of operators in Python is determined by the language.
See https://docs.python.org/3/reference/expressions.html#operator-precedence.
Unary - has a higher precedence than binary + (or binary -).

In SymPy, -x is represented as (-1)*x, but this is done after Python
parses the expression and converts them into SymPy objects.

In Python, x - y is different from x + -y. In the former, - is a
binary operator and the latter it is a unary operator. They both use
the same symbol because it's unambiguous which is which. SymPy
represents these both as x + (-1)*y because this makes things simpler,
but this is only because it converts them both to that canonical form.

Aaron Meurer

On Wed, Mar 24, 2021 at 2:13 PM Paul Royik <distan...@gmail.com> wrote:
>
> Is there any reason why precedence of -x equals precedence of Add?
> -x is (-1)*x
>
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/604cbda3-7b2f-4bb7-af4c-2f3b532edaa5n%40googlegroups.com.

Paul Royik

unread,
Mar 25, 2021, 3:18:26 AM3/25/21
to sympy
from sympy.printing.precedence, PRECEDENCE
precedence(-x) == PRECEDENCE['Add']
It gives True.

Aaron Meurer

unread,
Mar 25, 2021, 3:55:06 AM3/25/21
to sympy
The precedence in the printers is just about where it needs to add
parentheses. I suppose negation is the same as Add because it doesn't
require parentheses for anything with a higher precedence. For
instance -x*y is fine rather than -(x*y), but -(x + y) requires the
parentheses.

Aaron Meurer
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/dc0c166a-3c9f-42f8-bc9a-b4acc504d4d3n%40googlegroups.com.

Paul Royik

unread,
Mar 25, 2021, 10:03:52 AM3/25/21
to sympy
You examples would work even if precedence of negation equals precedence of Mul.
And PRECEDENE['Add'] doesn't work for Unevaluated(-x)*y. It will output (-x)*y.
Negation is just a Mul.
Reply all
Reply to author
Forward
0 new messages