Saturday, August 13, 2022

[FIXED] how to supress very small scientific notations to zero?

Issue

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


Solution

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
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.