Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy Set Values In Range Above And Below Zero To Zero

I’m building a optimization model with numpy and i have matrices with the values of 1e-17 and also -1e-17 i would like to set them to zero in a range of lets say 1e-8 above and below zero so that the matrix coefficients are not as big.

I found this
a = [0 if a_ > thresh else a_ for a_ in a] in another post. But this only works for non negative values.
I tried adding another threshhold like this:
a = [0 if a_ > thresh and a_<thresh2 else a_ for a_ in a]

This gave an error message: "The truth value of an array with more than one element is amniguous. Use a.any() or a.all()."
I added this like this: a = [0 if (a_ > thresh and a_<thresh2).all() else a_ for a_ in a].
This did not work either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a simple solution to this problem? Any ideas on how to solve this?

>Solution :

I think you want the absolute value to be compared to the threshold?
It should be a builtin in python.


a = [0 if abs(a_) > thresh else a_ for a_ in a]

In case I’m missing something about python’s treatment of small numbers without numpy, there’s also a numpy.absolute(a_) function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading