I have a linear equation of a form ax=b where b is a complex matrix, and a is a real matrix. I’m expecting solution x to be a complex vector. When trying the numpy.linalg.solve(a,b)
function, I’m getting this warning:
ComplexWarning: Casting complex values to real discards the imaginary part
How do I solve this equation to preserve the complex numbers?
Advertisement
Answer
Split b
into its real and imaginary components and solve the real/imaginary parts separately
Ax = b = A(xr+xi) = br + bi
A @ xr = br, A @ xi = bi
JavaScript
x
7
1
br = np.real(b)
2
bi = np.imag(b)
3
A_inv = np.linalg.inv(A)
4
xr = A_inv @ br
5
xi = A_inv @ bi
6
x = xr + 1.j*xi
7
EDIT The way you want to do it:
JavaScript
1
2
1
x = np.linalg.solve(A, np.real(b)) + 1.j*np.linalg.solve(A, np.imag(b))
2