sympy 因子简单关系 [英] sympy factor simple relationship

查看:24
本文介绍了sympy 因子简单关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 sympy 中有一个简单的分解问题,我无法解决.我在 sympy 处理相当复杂的积分方面取得了巨大的成功,但我对一些简单的事情感到困惑.

我如何获得

phi**2 - 2*phi*phi_0 + phi_0**2 - 8

分解为

(phi - phi_0)**2 - 8

?

我已经尝试过因子函数

factor(phi**2 - 2*phi*phi_0 + phi_0**2 - 8,phi-phi_0)

产生相同的旧解决方案.

解决方案

正如我在评论中指出的,这种部分分解"并不是唯一的(例如,x**2 + 5*x + 7 等于 (x + 2)*(x + 3) + 1(x + 1)*(x + 4) + 3,一旦你明白这是怎么回事不难想出你自己的例子).

有一些方法可以手动执行此类操作,但很难知道该告诉您什么,因为我不知道您要寻找什么通用性.例如,执行此特定示例的最简单方法可能是

<预><代码>>>>打印(A.subs(p x + phi_0).factor().subs(x, phi - phi_0))(phi - phi_0)**2 - 8

也就是说,让 x = phi - phi_0(SymPy 不够聪明,无法用 x 替换 phi - phi_0,但它足够聪明,可以用 x - phi_0 替换 phi,这是同一件事).如果您想考虑更大的多项式,或者您不知道自己的目标是什么,那么这不能很好地概括.但是考虑到变量的名称,我猜 phi - phi_0 就是你关心的全部.

除此之外,我应该指出,您可以通过深入研究并编写自己的算法来挖掘表达式,从而或多或少地进行任何您想要的简化.看看 http://docs.sympy.org/latest/tutorial/manipulation.html 让你开始.还要看看 Expr 的所有方法.如果您最终编写了这样的东西,那么有很多有用的辅助函数,例如各种 as_* 方法.

I have a simple factorization problem in sympy that I cannot sort out. I've had great success with sympy working with quite complex integrals, but I'm flummoxed by something simple.

How do I get

phi**2 - 2*phi*phi_0 + phi_0**2 - 8

to factor to

(phi - phi_0)**2 - 8

?

I've already tried the factor function

factor(phi**2 - 2*phi*phi_0 + phi_0**2 - 8,phi-phi_0)

which yields the same old solution.

解决方案

As I noted in the comment, such "partial factorizations" are not unique (for instance, x**2 + 5*x + 7 equals (x + 2)*(x + 3) + 1 and (x + 1)*(x + 4) + 3, and once you understand what's going on it's not hard to come up with examples of your own).

There are ways to do such things manually, but it's hard to know what to tell you because I don't know what generality you are looking for. For instance, probably the easiest way to do this particular example is

>>> print(A.subs(phi, x + phi_0).factor().subs(x, phi - phi_0))
(phi - phi_0)**2 - 8

That is, let x = phi - phi_0 (SymPy isn't smart enough to replace phi - phi_0 with x, but it is smart enough to replace phi with x - phi_0, which is the same thing). This doesn't generalize as nicely if you want to factor in terms of a larger polynomial, or if you don't know what you are aiming for. But given the names of your variables, I'm guessing phi - phi_0 is all you care about.

Beyond this, I should point out that you can more or less do any kind of simplification you want by digging in and writing your own algorithms that dig into the expressions. Take a look at http://docs.sympy.org/latest/tutorial/manipulation.html to get you started. Also take a look at all the methods of Expr. There are quite a few useful helper functions if you end up writing such a thing, such as the various as_* methods.

这篇关于sympy 因子简单关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆