Home > Enterprise >  how to supress very small scientific notations to zero?
how to supress very small scientific notations to zero?

Time:08-12

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

CodePudding user response:

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.    ]])

CodePudding user response:

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.    ]]
  • Related