I have a couple of situations where I need to clamp a floating-point number to the upper or lower end of an arbitrary[1] range. Thus far, I have been using floor
and ceil
functions with pre- and post-scaling, as follows:
y*floor(x/y) - x + y
y*ceil(x/y) - x - y
Where y
specifies the size of the range that we're snapping to. That works, but it feels inelegant, and these calculations happen often enough to be an actual performance bottleneck. Now, it turns out that x mod y = x - y*floor(x/y)
, which means with a little algebra that first expression can be simplified to y - (x mod y)
, which is only two operations rather than five, and eliminates a multiply.
I am, however, having considerably more difficulty figuring out how to replace ceil
without using branching (which would not do any good for performance). So, is there any way to re-write y*Math.ceil(x/y)
that would give me opportunities for algebraic simplification, or am I just stuck with this?
[1] In case it helps, y
is always an integer power of two, and the exponent is cached and available for use.