Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore Python warnings for complex numbers

I have a list that I need to include both real values and complex values. However, when I don't initialize the array using numpy.zeros(dtype=complex), I get the following error:

n[2] = 3.7095 + 0.007j

TypeError: can't convert complex to float

However, when I do set the dtype to complex, I get the following warning when I use a real number (which doesn't break my code, but it causes a ton of unnecessary red warning messages that clutter my console:

ComplexWarning: Casting complex values to real discards the imaginary part

How can I disable the warning message, or set it up another way so the values can be imaginary or complex?

like image 279
Zach G Avatar asked Sep 06 '25 12:09

Zach G


2 Answers

You can use this to ignore warning messages:

import warnings
warnings.filterwarnings('ignore')

Documentation: https://docs.python.org/2/library/warnings.html

I have included the link of the documentation as there are also more "soft" methods to deal with warning, such as printing only the first occurrence of the warning ('once'). It is also possible to filter only certain classes of warnings (ComplexWarning) in your case.

like image 194
FLab Avatar answered Sep 08 '25 03:09

FLab


for pytorch I used this method because i didn't need the imaginary part :

complex_tensor = complex_tensor.real # this will keep the real part of the tensor


print(complex_tensor.dtype) #this will return the previous data type of the complex_tensor

If your tensor was complex from the start ,it wil turn into a float64

like image 43
abtin rashidi Avatar answered Sep 08 '25 01:09

abtin rashidi