Home > Mobile >  Numpy Set Values In Range Above And Below Zero To Zero
Numpy Set Values In Range Above And Below Zero To Zero

Time:01-12

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.

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

CodePudding user response:

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.

  • Related