如何在表达式中替换多个符号?

时间:2022-04-29 20:19:35

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

3 个解决方案

#1


19  

To substitute several values:

要替换几个值:

>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30

#2


1  

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)

实际上,只有在你真的想用子代替它们时才设想不要替换值(参见http://docs.sympy.org/latest/tutorial/basic_operations.html)

Try

尝试

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

instead of

代替

x = 0

#3


1  

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.

命令x = Symbol('x')将Sympy的符号('x')存储到Python的变量x中。之后创建的Sympy表达式f包含Symbol('x'),而不是Python变量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').

重新分配x = 0时,Python变量x设置为零,并且不再与Symbol('x')相关。这对Sympy表达式没有影响,该表达式仍包含符号('x')。

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

Sympy文档的这一页最好地解释了这一点:http://docs.sympy.org/latest/gotchas.html#variables

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

你要做的是f.subs(x,0),如其他答案所述。

#1


19  

To substitute several values:

要替换几个值:

>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30

#2


1  

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)

实际上,只有在你真的想用子代替它们时才设想不要替换值(参见http://docs.sympy.org/latest/tutorial/basic_operations.html)

Try

尝试

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

instead of

代替

x = 0

#3


1  

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.

命令x = Symbol('x')将Sympy的符号('x')存储到Python的变量x中。之后创建的Sympy表达式f包含Symbol('x'),而不是Python变量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').

重新分配x = 0时,Python变量x设置为零,并且不再与Symbol('x')相关。这对Sympy表达式没有影响,该表达式仍包含符号('x')。

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

Sympy文档的这一页最好地解释了这一点:http://docs.sympy.org/latest/gotchas.html#variables

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

你要做的是f.subs(x,0),如其他答案所述。