Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

Chop[expr] replaces approximate real numbers in expr that are close to zero by the exact integer 0.

Details

  • Chop[expr,delta] replaces numbers smaller in absolute magnitude than delta by 0.
  • Chop uses a default tolerance of 10-10.

Therefore I want to ask if there is any function like this in Python.

like image 937
JoeJackJessieJames Avatar asked May 03 '17 05:05

JoeJackJessieJames


1 Answers

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
    ]
like image 110
Markus Meskanen Avatar answered Sep 19 '22 22:09

Markus Meskanen