subs finds all instances of an expression and tries to replace them.
It takes into account mathematical knowledge (e.g., (4*x).subs(2*x, y)
will work, even though strictly speaking, 2*x is not part of the
expression tree of 4*x).
replace uses several methods to let you do more advanced substitutions
based on patterns. It does not substitute objects directly:
In [7]: x.replace(x, y)
Out[7]: x
In [8]: x.subs(x, y)
Out[8]: y
Rather, you use either a function or an expression with a Wild to
replace general expressions. For example
In [10]: a = Wild('a')
In [11]: (sin(x) + sin(x**2)).replace(sin(a), cos(a))
Out[11]:
⎛ 2⎞
cos(x) + cos⎝x ⎠
To do this with subs, you would have to manually gather all the sin's
in the expression (using .atoms(sin)) and build a replacement
dictionary of corresponding cosines. replace lets you do this in one
step. You can achieve the same thing using the function forms (e.g.,
expr.replace(sin, cos)).
The third option is xreplace. This is like a very stripped down
version of subs. It does not do any mathematical reasoning. In order
for the expression to be replaced, it must appear exactly as given in
the dictionary in the expression tree (another way to say this is that
it will appear in expr.atoms(type(old))). Use this if you want to
avoid the mathematical reasoning of subs from messing with you too
much. If you got your replacement dictionary keys using atoms, you
should probably be using xreplace. A common example where subs and
xreplace act differently is in replacing powers such as exponentials.
In [15]: (exp(x) + exp(2*x)).subs(exp(x), y)
Out[15]:
2
y + y
In [16]: (exp(x) + exp(2*x)).xreplace({exp(x): y})
Out[16]:
2⋅x
y + ℯ
So I would say, if you find yourself building complex substitutions
dictionaries, see if you can do it easier with replace. Regarding
subs vs. xreplace, consider how smart you want the replacement to be.
Do you want the replacement to try to happen as much as possible,
mathematically, or do you only want to replace the exact thing that
you found (or suspect might be) in your expression? Depending on how
you answer that question, use subs or xreplace, respectively.
This particular instance it seems was already fixed, but if you notice
any others, let us know. It usually just means that we have a minor
formatting error in the docstring, such as no empty line after the
heading.
Aaron Meurer
>
> Thank you!
>
> --
> Shriramana Sharma
>
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To post to this group, send email to
sy...@googlegroups.com.
> To unsubscribe from this group, send email to
sympy+un...@googlegroups.com.
> For more options, visit this group at
http://groups.google.com/group/sympy?hl=en.
>