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

defining symbols with same name but different options creates distinct symbols. Maybe warn? #20891

Open
felixniemeyer opened this issue Feb 1, 2021 · 1 comment
Labels
gotcha a known issue for Python

Comments

@felixniemeyer
Copy link

Today, I stumbled into a very subtle pitfall that might happen to you when writing more complex stuff with sympy (pythons symbolic mathematics library).

Maybe you define some symbols multiple times (e.g. because some live in a class, and some in the main program using that class). It works fine: same symbols will be recognized by sympy to be the same.

But here is the pitfall: if you pass different options when defining the symbols (e.g. positive=True for one definition, omitted for the other), you end up with sympy treating those two character-wise identical symbols as differing.

This will very probably lead to trouble.

In my case, sympy simply couldn't find a solution to an equation - because internally there were two symbols for what I expected to be the same.

Maybe there is a way to warn users or rise an error?

@Maelstrom6
Copy link
Contributor

This is expected behavior. Ideally, every instance should be treated completely different even if they have exactly the same attributes. Parts of the code sometimes use the same name for variables like '_n' which would lead to bugs if they were treated the same. This is part of the reason why Dummy was created I guess.

Here is how I go about sorting it out:

from sympy import *
x = symbols('x')

def multiply_by_x(expr: Expr):
    # this will be a function in a different
    # class that cant see x.
    # now we try to extract the x from expr
    # we need to know the string name of x though
    x = [sym for sym in expr.free_symbols if str(sym) == 'x'][0]
    # this x is now the same as the x outside the function
    
    # do stuff with the function
    return x * expr

print(multiply_by_x(sin(x)))

There are probably better ways of doing this but this seems the most straight-forward to me.
Otherwise you could always have multiply_by_x(expr, x). That way you pass all your symbols in as arguments. Now that I'm typing this, this second option seems far better.

@Maelstrom6 Maelstrom6 added the gotcha a known issue for Python label Feb 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
gotcha a known issue for Python
Projects
None yet
Development

No branches or pull requests

2 participants