Search code examples
pythonsymbolic-mathsympy

Sympy "global" substitution


I have a number of symbolic expressions in sympy, and I may come to realize that one of the coefficients is zero. I would think, perhaps because I am used to mathematica, that the following makes sense:

from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
f = x + y
x = 0
f

Surprisingly, what is returned is x + y. Is there any way, aside from explicitly calling "subs" on every equation, for f to return just y?


Solution

  • I don't think there is a way to do that automatically (or at least no without modifying SymPy).

    The following question from SymPy's FAQ explains why:

    Why doesn't changing one variable change another that depends it?

    The short answer is "because it doesn't depend on it." :-) Even though you are working with equations, you are still working with Python objects. The equations you are typing use the values present at the time of creation to "fill in" values, just like regular python definitions. They are not altered by changes made afterwards. Consider the following:

    >>> a = Symbol('a') # create an object with name 'a' for variable a to point to
    >>> b = a + 1; b    # create another object that refers to what 'a' refers to
    a + 1
    >>> a = 4; a        # a now points to the literal integer 4, not Symbol('a')
    4
    >>> b               # but b is still pointing at Symbol('a')
    a + 1
    

    Changing quantity a does not change b; you are not working with a set of simultaneous equations. It might be helpful to remember that the string that gets printed when you print a variable refering to a sympy object is the string that was give to it when it was created; that string does not have to be the same as the variable that you assign it to:

    >>> r, t, d = symbols('rate time short_life')
    >>> d = r*t; d
    rate*time
    >>> r=80; t=2; d    # we haven't changed d, only r and t
    rate*time
    >>> d=r*t; d        # now d is using the current values of r and t
    160