set very low values to zero in numpy

Hmmm. I'm not super-happy with it, but this seems to work:

>>> a = np.array([0 +  0.5j, 0.25 + 1.2352444e-24j, 0.25+ 0j, 2.46519033e-32 + 0j])
>>> a
array([  0.00000000e+00 +5.00000000e-01j,
         2.50000000e-01 +1.23524440e-24j,
         2.50000000e-01 +0.00000000e+00j,   2.46519033e-32 +0.00000000e+00j])
>>> tol = 1e-16
>>> a.real[abs(a.real) < tol] = 0.0
>>> a.imag[abs(a.imag) < tol] = 0.0
>>> a
array([ 0.00+0.5j,  0.25+0.j ,  0.25+0.j ,  0.00+0.j ])

and you can choose your tolerance as your problem requires. I usually use an order of magnitude or so higher than

>>> np.finfo(np.float).eps
2.2204460492503131e-16

but it's problem-dependent.


To set elements that are less than eps to zero:

a[np.abs(a) < eps] = 0

There could be a specialized function that is more efficient.

If you want to suppress printing of small floats instead:

import numpy as np
a = np.array([1+1e-10j])
print a # -> [ 1. +1.00000000e-10j]

np.set_printoptions(suppress=True)
print a # -> [ 1.+0.j]

By using the method round(n) of the array

np.array( [0 +  0.5j, 0.25 + 1.2352444e-24j, 
           0.25+ 0j, 2.46519033e-32 + 0j]  ).round(23)

You can also use the numpy.isclose method:

>>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
array([True, False])

By asking if it is close to zero, it should work:

>>> np.isclose([1e10,0], [1.00001e-10,0])
array([False, True])

You can customise the atol (absolute tolerance, defaults to 1e-08) and the rtol (relative tolerance, defaults to 1e-05) parameters. You can then set rtol=0 to only use the absolute tolerance.