Issue
I have an array Sum
with some elements being very small. I want to print this array based on a tolerance value, tol
such that if any element is less than this, it becomes zero. I present the expected output.
import numpy as np
tol = 1e-12
Sum = np.array([ 7.37551766e-08, -4.99999992e-17, 0.00000000e+00, 5.00000028e-16,
-4.99999984e-17, 0.00000000e+00, -4.83360759e-07])
for i in range(0,len(Sum)):
if (abs(Sum[i]) < tol):
Sum[i]==0
print(Sum)
The expected output is
[array([ 7.37551766e-08, 0, 0.00000000e+00, 0,
0, 0.00000000e+00, -4.83360759e-07])]
Solution
Two easy solutions:
Solution 1
You can apply a simple mask:
Sum[np.abs(Sum) < tol] = 0.0
This is a simple one-liner, ideal if you only want to zero-out some elements.
Solution 2
You could map over the array with a function that returns 0 when input is under threshold:
def f(x, threshold):
return x if x>threshold else 0.0
tol = 1e-12
Sum = np.vectorize(lambda x: f(x, tol))(Sum)
The advantage of this solution is that you can easily do more complex operations on your elements by modifying the function f(x, threshold)
. The drawback is that is a little bit longer.
Time efficiency
Using a simple boolean mask is way more efficient, see the figure and note the logarithmic axes.
Answered By - Kins
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.