I have a big matrix with lots of elements extremely small, and I consider these elements as 0. In Mathematica, there is a function called Chop
:
Chop[expr]
replaces approximate real numbers inexpr
that are close to zero by the exact integer 0.Details
Chop[expr,delta]
replaces numbers smaller in absolute magnitude thandelta
by 0.Chop
uses a default tolerance of 10-10.
Therefore I want to ask if there is any function like this in Python.
There's no built-in function for this, but you can easily create one yourself:
def chop(expr, *, max=0.3):
return [i if i > max else 0 for i in expr]
Calling this would convert all numbers less than or equal to 0.3
to a 0
:
>>> chop([1.0, 0.2, 0.4, 0.3, 0.31])
[1.0, 0, 0.4, 0, 0.31]
You should change the default value of max
to something that suits your needs better, but you can always change it separately for individual calls too:
>>> chop([0.2, 0.3, 0.4], max=0.25)
[0, 0.3, 0.4]
>>> chop([0.3, 1, 2, 3], max=2)
[0, 0, 0, 3]
And if you want, you can convert negative numbers too! Either using the same distance from zero for both positive and negative numbers:
def chop(expr, *, max=0.3):
return [i if abs(i) > max else 0 for i in expr]
Or by using two different limits:
def chop(expr, *, max=0.3, min=-0.3):
if max < min:
raise ValueError
return [
i if i > max or i < min else 0
for i in expr
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With