Result of subtraction either positive or zero I need to perform a subtraction where the result must be either positive or zero. I will use some pseudo code to represent what I mean (like it is not clear enough but still).
function subtract(x, y) {
    result = x - y

    if (result < 0) {
        result = 0
    }

    return result
}

Now as a programmer I know my ways around math, but I am far from a mathematician. I would like to ask if there is any math wizardry that would do this for me instead of having to check the result before returning it, something like an absolute value - if there was no absolute value function I would have to check if the number is less than 0 and if yes multiply by -1. I hope I'm making sense.
P.S.: I'm completely unaware of what tags to use for this, please excuse me and edit if possible.
 A: I suggest $\max\{0, x-y\}$, the maximum of zero and $(x-y).$
A: You are writing a program — you don't want math wizardry, you want programming wizardry.
Math wizardry will tend to aim for expressing things in terms that are convenient to work with for various mathematical purposes.
But what you need is something that:


*

*Makes for an efficient program

*Is easy for programmers to read


and the thing is, what you've written is already pretty much optimal for that purpose.
(I assume now you are writing in something like C or C++)
In fact, I would actually expect the entire if statement to be translated to a single machine language instruction: there are two likely possibilities depending on the architecture:


*

*a conditional move depending on the sign of the previous arithmetic instruction

*a max instruction, if your architecture has one


You basically can't do better than that unless your architecture offers a single instruction whose job is to do exactly what your function does — and even then it's the job of the compiler to recognize that and choose that instruction, rather than you writing an arcane program.
A: Try
$$
\text{result} = (|x-y|+x-y)/2
$$
If $x\geqslant y$, then $\text{result} =x-y$ and if $x<y$, then $\text{result} =0$
A: What if your function was something like this?
function subtract( x, y ) {
    if( x < y ) // difference will be negative
        return 0;
    else
        return x - y;
}

A: One can completely avoid the unpleasant cache effects of a branch by using the pre-calculated sign bit. 
Update - corrected hurried misreading of spec.
/// <summary>Return difference of operands, or zero if negative.</summary>
function subtract(x, y) {
    result = x - y

    return result * (1 + Math.Sign(result) ) / 2;
}

This code is simply arithmetic operations, all of which are highly optimized on modern CPU's.
A: Your code looks like Javascript, in which case you should have written:
function subtract(x,y) { return ( x<y ? 0 : x-y ); }

This is both the clearest and the fastest.
