Scott B
Scott B

Reputation: 2602

Python/Numpy - Set Values within some Tolerance to the Value

If I have an array and I want to set values 'close' to some value as that value, what is the best way to do this? I'm wondering if their is a numpy function for this. If there is no numpy function, then is the code below the "best" (i.e. quickest/most efficient) way to do this? It works for multi-dimensional arrays as well.

Code:

from numpy import array
tol = 1e-5

# Some array with values close to 0 and 1
t = array([1.0e-10, -1.0e-10, 1.0+1.0e-10, 1.0-1.0e-10, 5.0])
print t[0], t[1], t[2], t[3], t[4]

# Set values within 'tol' of zero to zero
t[abs(t) < tol] = 0.
print t[0], t[1], t[2], t[3], t[4]

# Set values within 'tol' of some value to that value
val = 1.
t[abs(t-val) < tol] = val
print t[0], t[1], t[2], t[3], t[4]

Upvotes: 4

Views: 14583

Answers (2)

eat
eat

Reputation: 7530

It's not so quite clear what you are trying to achieve, but my interpretation is that around is the solution for your case.

Upvotes: 3

Related Questions