简体   繁体   English

sympy - 替代特定的权力

[英]sympy - substitute a specific power

I have this equality.我有这种平等。

import sympy as sp
D, L, V = sp.symbols("D, L, V", real=True, positive=True)
Veq = sp.Eq(V, sp.pi * D**3 / 4 * (sp.Rational(2, 3) + L / D))

I would like to solve Veq for D**3 .我想为D**3解决Veq If I try a direct approach, sp.solve(Veq, D**3) the computation is going to take a while eventually giving me a tremendously long result (useless to me).如果我尝试直接方法, sp.solve(Veq, D**3)计算将需要一段时间,最终会给我一个非常长的结果(对我没用)。

My attempt: trying to substitute D**3 with a new symbol, then solve for it.我的尝试:尝试用新符号替换D**3 ,然后解决它。 Unfortunately, the substitution is also going to replace the other D in the equality:不幸的是,替换也将替换等式中的另一个D

t = sp.symbols("t")
print(Veq.subs(D**3, t))

>>> Eq(V, pi*t*(L/t**(1/3) + 2/3)/4)

Note the term L/t**(1/3) .注意术语L/t**(1/3) I would like it to be L/D after the substitution.我希望它在替换后是L/D So far I've managed to manipulate the expression and reaching my goal with this code:到目前为止,我已经设法操纵表达式并使用以下代码实现了我的目标:

res = sp.Mul(*[a.subs(D**3, sp.symbols("t")) if a.has(D**3) else a for a in asd.args[1].args])
Veq = sp.Eq(V, res)
print(Veq)

>>> Eq(V, pi*t*(2/3 + L/D)/4)

I'm wondering, is there some flag for subs that I can use to reach my goal?我想知道,是否有一些subs标志可以用来实现我的目标? Or some other method?或者其他什么方法?

If you want the substitution to be exact you can use the exact flag:如果您希望替换准确,您可以使用exact标志:

>>> var('D V L')
(D, V, L)
>>> Veq = sp.Eq(V, sp.pi * D**3 / 4 * (sp.Rational(2, 3) + L / D))
>>> Veq.subs(D**3,y,exact=True)
Eq(V, pi*y*(2/3 + L/D)/4)
>>> solve(Veq.subs(D**3,y,exact=True),y)
[12*D*V/(pi*(2*D + 3*L))]

The exact flag appears to be ignore when assumptions are given:当给出假设时, exact标志似乎被忽略:

>>> D, L, V = symbols("D, L, V", real=True, positive=True)
>>> (D**3+D).subs(D**3,y,exact=True)
y**(1/3) + y
>>> D, L, V = symbols("D, L, V")
>>> (D**3+D).subs(D**3,y,exact=True)
D + y

You can use replace for your situation:您可以针对您的情况使用replace

>>> D, L, V = symbols("D, L, V", real=True, positive=True)
>>> (D**3+D).replace(D**3,y)
D + y

But since your expression is a Relational you have to use replace on the arguments, not the Relational (or else you will get an error):但是由于您的表达式是关系式,您必须在参数上使用替换,而不是关系式(否则您将收到错误):

>>> eq = Eq(D**3, D - 1)
>>> eq.func(*[a.replace(D**3,y) for a in eq.args])
Eq(y, D - 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM