Xiaoshu
Xiaoshu

Reputation: 211

How to work out ''ComplexWarning: Casting complex values to real discards the imaginary part''?

I would like to use a matrix with complex entries to construct a new matrix, but it gives me the warning

"ComplexWarning: Casting complex values to real discards the imaginary part".

As a result, the new matrix's entries are all real numbers. How to make all the entries keep their imaginary part?

This is the image containing my original code

This is the image containing my original code

Upvotes: 9

Views: 60192

Answers (2)

Xiaoshu
Xiaoshu

Reputation: 211

I know where I make this warning happen.

I need to add dtype = "complex_", when I construct a new empty matrix.

For example,

mat__ = np.zeros((k*nboxes,k*nboxes),dtype = 'complex_')

If we just write

mat__ = np.zeros((k*nboxes,k*nboxes))

and do some manipulations on that like using a complex matrix to forming a new matrix, then the new matrix will discard the imaginary part.

Upvotes: 12

Hoog
Hoog

Reputation: 2298

You could try using numpy to create a new matrix from your Matrix_1 with the array constructor. That way you can specify that you are using Complex numbers with the dtype. Something like this should do the trick:

mat_ = np.array(matrix_1[:,ll,ll,:],dtype = "complex_")

Some testing that I used to make sure:

import numpy as np

abc = np.array([[1+1j,2+2j,3+3j],[4+4j,5+5j,6+6j],[7+7j,8+8j,9+9j]],dtype = "complex_") # initial
print(abc)
abc2 = np.array(abc[1:,:1],dtype = "complex_") # post transformation
print(abc2)

Upvotes: 0

Related Questions