问题描述
我正在尝试进行一些基本的替换,但 SymPy 不想帮我
I'm trying to make some basic substitutions but SymPy doesn't want to help me out
x, y, z, k = symbols("x y z k", positive=True, real=True)
exp = x**4 + x**3 + x**2 + x
what_im_expecting = simplify(y**(Rational(1/4)) + y**(Rational(3/4)) + sqrt(y) + y)
what_i_actually_get = exp.subs(x**4,y)
exp, what_i_actually_get, what_im_expecting
返回
x + y**(Rational(3, 4)) + sqrt(y) + y
有人可以帮我吗?
一个更复杂的例子:
推荐答案
可以信任方法 subs
替换与给定的旧"表达式完全匹配的术语,其中 x**4
在这里.其他与x**4
相关的东西的替换就不是那么确定了.(有 许多未解决的问题与 subs:有人说它替代太多,有人说太少.)有一些特定于 powers 的替代逻辑,但 x
本身不是正式的权力,所以它逃避了这个逻辑.解决方法:暂时将 x
替换为 x**1
,防止自动评估 x
的权力.
The method subs
can be trusted to replace the terms that exactly match the given "old" expression, which x**4
here. The replacement of other things related to x**4
is not so certain. (There are many open issues with subs: some say it substitutes too much, some say too little.) There is some substitution logic specific to powers, but x
by itself is not formally a power, so it escapes that logic. A workaround: temporarily replace x
by x**1
, preventing automatic evaluation of that power to x
.
x1 = sp.Pow(x, 1, evaluate=False)
subbed = exp.subs(x, x1).subs(x**4, y).subs(x1, x)
现在subbed
是y**(3/4) + y**(1/4) + sqrt(y) + y
.
但是,不要期望 subs
具有人类般的创造力.使用相同的解决方法,尝试执行 subs(x**4 - 1, y)
会导致 x**3 + x**2 + x + y + 1
: 没有像 sqrt(y+1)
之类的东西出现.最好以最直接的方式替换:
But, don't expect human-like ingenuity from subs
. With the same workaround, trying to do subs(x**4 - 1, y)
results in x**3 + x**2 + x + y + 1
: nothing like sqrt(y+1)
, etc, appears. It's better to substitute in the most direct way possible:
subs(x, (y+1)**Rational(1, 4))
那么您就不需要任何解决方法了.
Then you don't need any workarounds.
这篇关于Sympy Subs 在更换电源时不更换符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!