Subtract Unless Negative Then Return 0

Question:

I’ll preface with, this is solely to satisfy my curiosity rather than needing help on a coding project. But I was wanting to know if anyone knows of a function (particularly in python, but I’ll accept a valid mathematical concept) kind of like absolute value, that given a number will return 0 if negative or return that number if positive.

Pseudo code:

def myFunc(x):
    if x > 0:
        return x
    else:
        return 0

Again, not asking the question out of complexity, just curiosity. I’ve needed it a couple times now, and was wondering if I really did need to write my own function or if one already existed. If there isn’t a function to do this, is there a way to write this in one line using an expression doesn’t evaluate twice.

i.e.

myVar = x-y if x-y>0 else 0

I’d be fine with a solution like that if x-y wasn’t evaluated twice. So if anyone out there has any solution, I’d appreciate it.

Thanks

Asked By: Hoopdady

||

Answers:

This should do it:

max(x-y, 0)
Answered By: Daniel Roseman

One way…

>>> max(0, x)
Answered By: Rob Cowie

Sounds like an analysis type question. numpy can come to the rescue!

If you have your data in an array:

x = np.arange(-5,11)
print x
[-5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10]

# Now do your subtraction and replacement.  
x[(x-y)>0] -= y
x[(x-y)<0]  = 0

If I understand your question correctly, you want to replace values in x where x-y<0 with zeros, otherwise replace with x-y.

NOTE, the solution above works well for subtracting an integer from an array, or operating on two array of equal dimensions. However, Daniel’s solution is more elegant when working on two lists of equal length. It all depends on your needs (and whether you want to venture into the world of numpy or not).

Answered By: tnknepp

An alternative expression would be

x -= min(x, y)
Answered By: user3335499
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.