Sympy substitutions using subs (x, w) strings instead of subs (x, w) characters

I am working on an ahkab circuit simulator application and a short short history I need to substitute the variable laplace s in some equations with 1j * w. It’s much more convenient for me to perform this substitution, while others use symbol names rather than the symbols themselves. I came across some strange behavior.

If you do

    >>> x = Symbol('x')
    >>> y = Symbol('y')
    >>> expr = x + y
    x + y
    >>> expr.subs('x', 'w')
    w + y

It seems that I am working as I expect. The problem is that the character is declared using complex = True, here

    >>> s = Symbol('s', complex = True)
    >>> y = Symbol('y')
    >>> expr = s + y
    s + y
    >>> expr.subs(s, 'w') #Works as expected
    w + y
    >>> expr.subs('s', 'w') #Has no effect, this is my problem.
    s + y

I could not find the substitution information in this way in the docs. This seems like a mistake to me, but I don’t know what the behavior should look like.

+4
source share
2

subs sympify . . https://github.com/sympy/sympy/blob/master/sympy/core/basic.py#L845, . , , sympify , , , . - . , .

In [1]: from sympy import Symbol

In [2]: x = Symbol('s')

In [3]: y = Symbol('s')

In [4]: x == y
Out[4]: True

In [5]: y = Symbol('s', complex=True)

In [6]: x == y
Out[6]: False
+4

Symbol . , :

from sympy import Symbol as _Symbol

class SymbolCollection(dict):
    def __missing__(self, key):
        value = self[key] = _Symbol(key)
        return value

symbs = SymbolCollection()
def Symbol(key, *args, **kwargs):
    s = _Symbol(key, *args, **kwargs)
    symbs[key] = s
    return s

:

>>> s = Symbol('s', complex = True)
>>> y = Symbol('y')
>>> expr = s + y
>>> expr
s + y
>>> expr.subs(s, symbs['w'])
w + y
>>> expr.subs(symbs['s'], symbs['w'])
w + y

, subs expr , .subs

0

All Articles