I have a big numpy 2d array F
which has complex numbers (np.complex64
). It has a lot of very small numbers. For the sake of my calculation, I only need precision of ~1e-6 - 1e-9. Since this matrix is very large, I am trying to use a sparse matrix representation. So I try to do this:
np.seterr(all="raise")
...
F = getF()
F[np.abs(F) < EPSILON] = 0
# EPSILON = 1e-9. It is supposed to be in between 1e-6 and 1e-9
return csr_matrix(F)
But the computing the absolute value gives an underflow error (with numpy set to raise errors):
FloatingPointError: underflow encountered in absolute
Numpy doesn't raise an error if the seterr
is not done, but just puts out NaNs which leads to problems as this matrix F is the starting point of a series of calculations.
From what I have read, the underflow is mainly handled by taking log and using the log values directly instead of the main ones, but in this case, I want to discard them all anyway. Is there a sane way of doing so? I thought of np.clip
but I have complex number data so using it is not very straightforward.
So my question is whether there exists an elegant (and hopefully canonical) way of handling this?
First of, I can reproduce your error. As dawg pointed our this doesn't happen if you take
float
instead ofcomplex
. This is also the reason why option B works as the real and imag part are both arrays of floats. Another option (C) would be to use more bits to represent your data, I guess complex128 is the default for numpy.