Python 如何在sympy的表达式中替换多个符号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32930284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to substitute multiple symbols in an expression in sympy?
提问by Wesley
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
采纳答案by Wesley
To substitute several values:
替换多个值:
>>> from sympy import Symbol
>>> x, y = Symbol('x y')
>>> f = x + y
>>> f.subs({x:10, y: 20})
>>> f
30
回答by MSeifert
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)
实际上,sympy 旨在不替换值,直到您真的想替换它们subs
(请参阅http://docs.sympy.org/latest/tutorial/basic_operations.html)
Try
尝试
f.subs({x:0})
f.subs(x, 0) # as alternative
instead of
代替
x = 0
回答by Adrien
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 存储Symbol('x')
到 Python 的变量中x
。f
您之后创建的 Sympy 表达式确实包含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 表达式没有影响,它仍然包含Symbol('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)
正如其他答案中所说,您想要做的是。