how to supress very small scientific notations to zero?

Question:

In sub-list of b the numbers are very close to zero , i wanted to make it equal to zeros if, they are >-1e-05.

is there is any better method ?


b = [[0.0, -2.220446049250313e-16, -8.881784197001252e-16, -6.661338147750939e-16, 0.0],
     [0.0, -0.1875000, -0.1250000, -0.0625000, 0.0], 
     [0.0, -0.125000, -0.25000, -0.1250, 0.0], 
     [0.0, -0.06250, -0.1250, -0.18750, 0.0], [0, 0, 0, 0, 0]]

for i in b:
    for j in i:
        if j > -1e-05:
            j = 0
        else:
            j = j

Asked By: walter white

||

Answers:

To do this, you can use numpy and np.where. First transform your list into an array:

import numpy as np

b = np.array(b)

Then use np.where to modify your array. The first argument is your condition, the second is the value you want your array to have when the condition is satisfied and the the third is the value you want your array to have when the condition is not satisfied:

>>> np.where(b>-10**(-5), 0, b)
array([[ 0.    ,  0.    ,  0.    ,  0.    ,  0.    ],
       [ 0.    , -0.1875, -0.125 , -0.0625,  0.    ],
       [ 0.    , -0.125 , -0.25  , -0.125 ,  0.    ],
       [ 0.    , -0.0625, -0.125 , -0.1875,  0.    ],
       [ 0.    ,  0.    ,  0.    ,  0.    ,  0.    ]])
Answered By: Romain Simon

Just do:

  import numpy as np
  np.round(b, 5)

Results in:

[[ 0.     -0.     -0.     -0.      0.    ]
 [ 0.     -0.1875 -0.125  -0.0625  0.    ]
 [ 0.     -0.125  -0.25   -0.125   0.    ]
 [ 0.     -0.0625 -0.125  -0.1875  0.    ]
 [ 0.      0.      0.      0.      0.    ]]
Answered By: Eelco van Vliet
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.