18 February 2012

The absolute difference between two double numbers

How would we create a function

      abs( double a, double b )

that returns the absolute value of the difference between a and b?

Edit 21/02/2012:
I embarrassingly have to admit that before posting this entry in the beginning I had spent about an hour attempting some fancy prancy bit masking solution (as one might do in a integer or long abs function) gazing at bit arrangements and getting myself into an utter dead end and 100+ lines of code. I decided that this might simply be the best solution I could come up with:

public static double abs(double a, double b)
{
    double diff = b > a ? b - a : a - b;
    return diff < 0 ? -diff : diff;
}

Too stupid to fail?