How to substitute multiple symbols in an expressio

2020-02-11 18:22发布

Assigning a variable directly does not modify expressions that used the variable retroactively.

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

>>> f
x + y

标签: python sympy
3条回答
贪生不怕死
2楼-- · 2020-02-11 18:27

To substitute several values:

>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30
查看更多
做自己的国王
3楼-- · 2020-02-11 18:33

Actually sympy is designed not to substitute values until you really want to substitute them with subs (see http://docs.sympy.org/latest/tutorial/basic_operations.html)

Try

f.subs({x:0})
f.subs(x, 0) # as alternative

instead of

x = 0
查看更多
▲ chillily
4楼-- · 2020-02-11 18:41

The command x = Symbol('x') stores Sympy's Symbol('x') into Python's variable x. The Sympy expression f that you create afterwards does contain Symbol('x'), not the Python variable x.

When you reassign x = 0, the Python variable x is set to zero, and is no longer related to Symbol('x'). This has no effect on the Sympy expression, which still contains Symbol('x').

This is best explained in this page of the Sympy documentation: http://docs.sympy.org/latest/gotchas.html#variables

What you want to do is f.subs(x,0), as said in other answers.

查看更多
登录 后发表回答