Does python have a similar "Chop" function in Mathematica?
I have a large matrix with many elements that are very small, and I count those elements to be 0. There is a function in Mathematica called Chop
:
Chop[expr]
replaces approximate real numbers inexpr
, close to zero, with exact integers 0.More details
Chop[expr,delta]
replaces numbers less thandelta
0 in absolute value .Chop
uses the default tolerance of 10 -10 .
So I want to ask if there is such a function in Python.
source to share
There is 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 will convert all numbers less than or equal 0.3
to 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 max
to whatever suits your needs better, but you can always change it separately for individual calls:
>>> 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! Or 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 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
]
source to share
One way to do it with numpy is to use a masked array:
>>> import numpy
>>> def chop(expr, delta=10**-10):
... return numpy.ma.masked_inside(expr, -delta, delta).filled(0)
>>> x = numpy.fft.irfft(numpy.fft.rfft([2, 1, 1, 0, 0, 0]))
>>> x
array([ 2.00000000e+00, 1.00000000e+00, 1.00000000e+00,
3.20493781e-17, -4.44089210e-16, -3.20493781e-17])
>>> chop(x)
array([ 2., 1., 1., 0., 0., 0.])
If you really don't want to use numpy for some reason, then here's a function that works for scalar values, lists, and multidimensional lists (matrices):
def chop(expr, delta=10**-10):
if isinstance(expr, (int, float, complex)):
return 0 if -delta <= expr <= delta else expr
else:
return [chop(x) for x in expr]
source to share