2

I want to return a number that doesn't exceed a limit I set. For example I want to do the equivalent of:

if (number >= limit)
    number = limit;
return number;

Is there a mathematical way of doing the equivalent of what I just described in just one line?

Hayden
  • 407
  • 1
  • 6
  • 15

2 Answers2

6

You could:

return Math.min(number, limit);

or:

return number >= limit ? limit : number;
assylias
  • 321,522
  • 82
  • 660
  • 783
2

There's also the following mathematical formula: (taken from here)

min(a,b) = 1/2 (a + b - |a - b|)

Code:

return ( number + limit - Math.abs(number - limit) ) / 2;

Now Math.abs looks pretty similar to Math.min (so there wouldn't be much point to using the above instead of simply Math.min), although you could easily replace that with the method presented here or here:

mask = n >> 31         // 11111111 for negative and 00000000 for positive
abs = (mask + n)^mask  // convert negative to positive in 2's complement
                       //    while not changing positive

Note:

If number + limit can overflow, this won't work. This can be changed to
number - Math.abs(...) + limit to avoid this, but then number - Math.abs(...) can still underflow - you just need to keep overflow in mind and select the option that would prevent over/underflow based on the range of the numbers, or go for the non-arithmetic option.

Also keep in mind that, assuming no over/underflow, if you're dealing with floating point values (float / double) rather than integral types, the result of the above won't necessarily return either of the values (because of the way floating point representation works).

Community
  • 1
  • 1
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138