Question

I am using sympy to generate the determinant in of a matrix:

from sympy import *

X1, Y1 = symbols ("X1 Y1")
x1, x2, x3, y1, y2, y3 = symbols ("x1 x2 x3 y1 y2 y3")
th12, th13 = symbols ("theta_{12} theta_{13}")

X2 = cos(th12)*X1-sin(th12)*Y1+x2-y1*cos(th12)-y1*sin(th12)
Y2 = sin(th12)*X1+cos(th12)*Y1+y2-x1*sin(th12)-y1*cos(th12)

X3 = cos(th13)*X1-sin(th13)*Y1+x3-y1*cos(th13)-y1*sin(th13)
Y3 = sin(th13)*X1+cos(th13)*Y1+y3-x1*sin(th13)-y1*cos(th13)

M=Matrix([[X1,Y1,1],[X2,Y2,1],[X3,Y3,1]])
Det=M.det()
print Det

If you run the code you will notice that it generates a very "long" expression. I would like to get an expression like:

X1**2 + Y1**2 + A*X1 + B*Y1 + C = 0 (equation of a circumference)

So I would like Python to generate the coefficients A, B and C. Basically I would like to group all the therms that share X1**2, all the therms that share Y1**2, etc.

If I insert numerical values for x1, x2, x3, y1, y2, y3, th12, th13 I can get an expression in the form that I need, but I would like to get also the coefficients A, B and C.

EDIT: correction in the Xi and Yi formulas, added more information.

Was it helpful?

Solution

collect is the right tool for this:

Example from the above link:

>>> collect(a*x**2 + b*x**2 + a*x - b*x + c, x)
c + x**2*(a + b) + x*(a - b) 

In your case (coefficients are not normalized here):

col = collect(Det, [X1, Y1], evaluate=False)
A = col[X1]
B = col[Y1]
C = col[S.One]

With evaluate=False, you will get a dict with the factors. Otherwise, you get the full expression.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top