[英]Does python have a similar function of “Chop” in Mathematica?
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
: 我有一个很大的元素非常小的矩阵,我认为这些元素为0.在Mathematica中,有一个名为
Chop
的函数:
Chop[expr]
replaces approximate real numbers inexpr
that are close to zero by the exact integer 0.Chop[expr]
在替换近似实数expr
可由所述准确的整数0接近于零。Details
细节
Chop[expr,delta]
replaces numbers smaller in absolute magnitude thandelta
by 0.Chop[expr,delta]
将绝对幅度小于delta
的数字替换为0。Chop
uses a default tolerance of 10 -10 .Chop
使用默认容差10 -10 。
Therefore I want to ask if there is any function like this in Python. 因此,我想问一下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
: 调用此方法会将小于或等于
0.3
所有数字转换为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: 您应该将
max
的默认值更改为更适合您需求的内容,但您也可以单独为单个调用更改它:
>>> 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
]
One way to do that with numpy would be to use a masked array: 使用numpy的一种方法是使用蒙面数组:
>>> 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): 如果你真的不想因某种原因使用numpy,那么这里有一个适用于标量值,列表和多维列表(矩阵)的函数:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.