Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Printing of UnevaluatedExpr needs parenthesis around Add terms #21955

Open
bjodah opened this issue Aug 26, 2021 · 4 comments · Fixed by #21994
Open

Printing of UnevaluatedExpr needs parenthesis around Add terms #21955

bjodah opened this issue Aug 26, 2021 · 4 comments · Fixed by #21994
Labels

Comments

@bjodah
Copy link
Member

bjodah commented Aug 26, 2021

Floating point "add" is non-associative, i.e. (x+y)+z often differs from x+(y+z). In SymPy Add (re)orders its arguments (for good reasons), but for representing e.g. an algorithm in finite precision this creates a problem (see e.g. Kahan summation on wikipedia).

Typically we use UnevaluatedExpr for situations like this:

>>> from sympy import UnevaluatedExpr as ue
>>> from sympy.abc import k,l,m
>>> ue(k+m)+l
l + k + m
>>> ue(k+m)+l + k
k + l + k + m

but, as you see the printer is not emitting the required parenthesis to make this useful for representing non-associative add.

Note that SymEngine gets this right:

>>> from symengine import Symbol as S, UnevaluatedExpr as UE
>>> x,y,z = map(S, 'xyz')
>>> UE(y + x) + z
z + (x + y)

I propose that we fix this in the printers (I suspect updating precedence for UnevaluatedExpr might be enough, I haven't tried yet though). At the very least, the code printers should output parenthesis, but I think it's reasonable for the StrPrinter to do so as well?

@vsuharnikov
Copy link

vsuharnikov commented Oct 5, 2021

It seems, there is a related issue with LaTeX:

import sympy
from IPython.display import display
from sympy.abc import x, y, z
expr = x - sympy.UnevaluatedExpr(y - z)
print(expr) # prints: x - (y - z)
display(expr) # prints: x - y - z
print(sympy.__version__) # 1.8

@bjodah
Copy link
Member Author

bjodah commented Oct 5, 2021

thanks for the report @vsuharnikov, have you tried with the master branch (or 1.9-rc1)?

@vsuharnikov
Copy link

@bjodah Same issue:

x - (y - z)
𝑥−𝑦−𝑧 
1.9rc1

@bjodah
Copy link
Member Author

bjodah commented Oct 8, 2021

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants