Fast Math: fast floor / round / ceil

Calling Math.floor() simply takes too long. The problem with optimizing is that you can’t simply cast the floatingpoint number to an integer, because that will result in invalid results for negative numbers. If we know our input values are in a specific range, we can safely add a certain (big) constant to the input, cast the guaranteed positive value to an integer and subtract the constant again.

The code is ~9x faster than Math.floor(). Replacing the doubles with floats makes it faster, but the results are rather… random, so don’t.


public class FastMath
{
   private static final int    BIG_ENOUGH_INT   = 16 * 1024;
   private static final double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT;
   private static final double BIG_ENOUGH_ROUND = BIG_ENOUGH_INT + 0.5;

   public static int fastFloor(float x) {
      return (int) (x + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT;
   }

   public static int fastRound(float x) {
      return (int) (x + BIG_ENOUGH_ROUND) - BIG_ENOUGH_INT;
   }

   public static int fastCeil(float x) {
       return BIG_ENOUGH_INT - (int)(BIG_ENOUGH_FLOOR-x); // credit: roquen
   }
}

Thanks Riven, I used this in libgdx. You might want to use my javadocs there, which give the valid input ranges:
http://code.google.com/p/libgdx/source/browse/trunk/gdx/src/com/badlogic/gdx/math/MathUtils.java#164

floor has an additional limitation cause by underflow. For the current constant, value on [-0x1.0p-40f, 0) will return 0 instead of -1.

ceil is, well, broken. But since ceil(x)=-floor(-x), it can be reworked as:


public static final int ceil(float x) 
{
  //return (int)(x + BIG_ENOUGH_CEIL) - BIG_ENOUGH_INT;
    return BIG_ENOUGH_INT - (int)(BIG_ENOUGH_FLOOR-x);
}