How to enforce sympy to handle simplification with complex numbers?

28 Views Asked by At

I am quite new on sympy and I try to make a matrix multiplication. The matrices are complex.

Here is the code

import sympy as sp

eps = sp.exp(2 * sp.pi * sp.I / 6)

eps_star = sp.conjugate(eps)

M = 1 / sp.sqrt(6) * sp.Matrix([
    [1, 1, 1, 1, 1, 1],
    [1, eps_star, -eps, -1, -eps_star, eps],
    [1, -eps, -eps_star, 1, -eps, -eps_star],
    [1, eps, -eps_star, -1, -eps, eps_star],
    [1, -eps_star, -eps, 1, -eps_star, -eps],
    [1, -1, 1, -1, 1, -1]
]).transpose()

Minv = sp.conjugate(M).transpose()

If you compute the product M * Minv that should give the identity matrix you get one on the diagonal, but off diagonal terms are not zero.

You get for example

1/3 -1/3 eps - 1/3 eps_star

This is actually zero, because it simplifies in 1/3 - 1/3 [2 cos (pi / 3)] = 1/3 - 1/3 = 0. I tried to apply the simplify or nsimplify methods but it does not give me zero. Maybe it is due to a floating error issue.

Is there a way to manage this using sympy without using the fact that you know which term is zero.

This matrix is actually used in my case to switch from one basis to another in which an operator is diagonal. At the end, the product I want to compute is thus Minv * H * M. With the current issue, its impossible to see that the result is diagonal.

Here is the H matrix:

alpha, beta = sp.symbols("alpha beta")
H = sp.Matrix([
    [alpha, beta, 0, 0, 0, beta],
    [beta, alpha, beta, 0, 0, 0],
    [0, beta, alpha, beta, 0, 0],
    [0, 0, beta, alpha, beta, 0],
    [0, 0, 0, beta, alpha, beta],
    [beta, 0, 0, 0, beta, alpha],
])
1

There are 1 best solutions below

1
Davide_sd On

You can rewrite exp in terms of trigonometric functions, then it will automatically simplify the result:

(M*Minv).rewrite(sp.cos)