# Trouble inverting complex matrix with numpy and scipy

I have some matrix-valued, complex data $$Z(f)$$ with $$f\in\{f_0,f_1,\dots\}$$ and $$Z(f_i)$$ being a 3x3 matrix. I require the inverse $$Z^{-1}(f)$$ in my workflow. After encountering some problems with my results, I cold narrow the issue down to the inversion, which seems to be performed not very accurately by numpy.linalg.inv and to a lesser extend also by scipy.linalg.inv.

As you can see in the plot of the off-diagonal element $$Z_{12}$$ below, at intermediate values $$10^3 applying the numpy inversion twice does not yield the original data $$Z$$. In the plot, the scipy inversion seems to have no issues, but using scipy to compute $$Z^{-1}Z$$ also does not result exactly in the unity matrix at these values of $$f$$.

While the condition number of $$Z(f)$$ diverges for $$f\rightarrow 0$$ as seen in the second plot below, I would like to understand why my issues can occur at intermediate $$f$$ values, and how to choose an inversion algorithm that minimizes such problems.

• So your matrices for $f$ in the $10^1$ to $10^3$ range are effectively singular? And assuming that the error after the first inversion is $\kappa·\mu$, then the error after the second inversion is $\kappa^2·\mu$, so that up to $f=10^6$ the error from the floating point operations is possibly as large as the true values. If you can, try the same computations with a multi-precision library like mpmath. Dec 7, 2021 at 16:59
• What does Z represent? If it is a physical system involving wave physics there may be analytical ways to improve the conditioning of Z. Dec 7, 2021 at 17:25
• @LutzLehmann Thank you for suggesting mpmath! The brute force approach of just increasing the decimal precision to 100 definitely eliminates the issues. For these relatively small matrices, this is a viable approach :) Dec 9, 2021 at 7:54
• @sssssssssssss Z is an impedance and you are right that there is a smarter analytical way to compute its inverse at low frequencies that avoids inverting a matrix with diverging condition number. I'm only interested in this inversion because I'm trying to prove that it is absolutely necessary to avoid the naive approach of just inverting Z, because the alternative way is a bit more involved. Dec 9, 2021 at 7:59
• Do you really need the inverse? Often it is not the correct thing to compute numerically. E.g. solving Zx = b is better than inverting. Dec 13, 2021 at 13:13