Zach G
Zach G

Reputation: 645

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?

Upvotes: 4

Views: 9488

Answers (1)

FLab
FLab

Reputation: 7476

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.

Upvotes: 3

Related Questions