I am trying to find the inverse of a matrix, however, sympy always multiplies the final answer by 4, thereby making the answer wrong. This multiplication also happens when I use the factor function.
Here is the matrix I want to change
import sympy as sy z = sy.symbols('z') t = sy.Matrix([[z, -1], [sy.Rational(1,4), z + 1]]) t.inv()
And here is the “wrong” answer it gives
The true answer is the same only NOT multiplied by 4. Why does sympy multiply the answer like this?
Update
To isolate the problem we can try to factor the determinant.
If we factor the determinant I expect the answer to be(z+1/2)**2 However this is the answer I get, it is divided by 4 and , multiplied by 2. The expected answer has to be exactly (z+1/2)^2 not the multiplied version sympy outputs.
d = t.det() print("I want to factor this") display(d) print("After factoring") display(sy.factor(d)) print(" n The right answer I was expecting") display((z+sy.Rational(1,2))**2)
The problem I am solving evolves the Z-transfrom and this multiplication of the factor is making the final answer wrong. The factors or poles has to be exactly what they are without any multiplication, ie the answer has to be exactly (z+1/2)^2
Is there a way to make sympy give me the exact factors?
Advertisement
Answer
Be careful with your words: there is nothing “wrong” about the answer that you get. You would prefer to have the answer in a different form and that’s fine but the answer given is correct.
You can get the form that you want if you factor over the Gaussian rationals:
In [41]: e = z**2 + z + Rational(1, 4) In [42]: e Out[42]: 2 1 z + z + ─ 4 In [43]: factor(e) Out[43]: 2 (2⋅z + 1) ────────── 4 In [44]: factor(e, gaussian=True) Out[44]: 2 (z + 1/2) In [45]: t.inv() Out[45]: ⎡ 4⋅z + 4 -1 ⎤ ⎢ ────────────── ─────────────────⎥ ⎢ 2 ⎛ 2 ⎞⎥ ⎢ 4⋅z + 4⋅z + 1 ⎜ z z 1 ⎟⎥ ⎢ 4⋅⎜- ── - ─ - ──⎟⎥ ⎢ ⎝ 4 4 16⎠⎥ ⎢ ⎥ ⎢ 1 4⋅z ⎥ ⎢──────────────── ────────────── ⎥ ⎢ ⎛ 2 1⎞ 2 ⎥ ⎢4⋅⎜- z - z - ─⎟ 4⋅z + 4⋅z + 1 ⎥ ⎣ ⎝ 4⎠ ⎦ In [46]: t.inv().applyfunc(lambda e: factor(e, gaussian=True)) Out[46]: ⎡ z + 1 1 ⎤ ⎢ ────────── ──────────⎥ ⎢ 2 2⎥ ⎢ (z + 1/2) (z + 1/2) ⎥ ⎢ ⎥ ⎢ -1 z ⎥ ⎢──────────── ──────────⎥ ⎢ 2 2⎥ ⎣4⋅(z + 1/2) (z + 1/2) ⎦