Skip to content Skip to sidebar Skip to footer

Sympy Factor Simple Relationship

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 simpl

Solution 1:

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.


Post a Comment for "Sympy Factor Simple Relationship"