Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract Unless Negative Then Return 0

Tags:

python

math

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

like image 962
Hoopdady Avatar asked Oct 04 '12 13:10

Hoopdady


People also ask

How do you return a 0 instead of a negative in Excel?

Show a Zero for a Negative Number Select cell or range of cells. Press the Shortcut key Control + 1 (Command +1 if you are using Mac) to open the Format Cells dialog box. Click on the Custom Option and enter the 0;”0″;0 into the input box. Click OK to apply the settings.

What is the rule for subtracting negatives and positives?

Addition: Different Signs, Subtract the Numbers If you're adding positive and negative numbers together, subtract the smaller number from the larger one and use the sign from the larger number.

How do you change negative numbers in Excel?

Convert negative numbers in place Add -1 to a cell and copy to the clipboard. Select the negative numbers you want to convert. Use Paste Special > Values + Multiply.


3 Answers

One way...

>>> max(0, x)
like image 102
Rob Cowie Avatar answered Oct 09 '22 02:10

Rob Cowie


This should do it:

max(x-y, 0)
like image 26
Daniel Roseman Avatar answered Oct 09 '22 02:10

Daniel Roseman


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).

like image 31
tnknepp Avatar answered Oct 09 '22 02:10

tnknepp