Depending on your usage, the fastFloor that turns -1.0 into -2 isn’t really that horrible.
It turns -0.99999999 to -1, and -1.00000001 to -2, so the error zone is infinitesimal. It happens to be exactly the values you get when sticking in integers into the fastFloor method, which can cause some problems, but if you’re purely in float land, you might never notice the error.
I use it (and have for a while) in minecraft to deal with the player leaving the map to negative coordinates. Sure, it means there’s an EXTREMELY THIN SLIVER of all blocks out there that get calculated as belonging to the wrong blocks, but I can live with that.
The error margin in my fast sqrt is worse.
But what riven just posted is even better as long as you know the size of your negative domain
It does lose some precision in the positive extremes, so don’t make BIG_ENOUGH_INT TOO large, or this happens:
private static final int BIG_ENOUGH_INT = Integer.MIN_VALUE / 4;
private static final float BIG_ENOUGH_FLOAT = BIG_ENOUGH_INT;
public static int fastFloor(float x) {
return (int) (x + BIG_ENOUGH_FLOAT) - BIG_ENOUGH_INT;
}
public static void main(String[] args)
{
int from = Integer.MAX_VALUE/4;
int rounded = fastFloor(from);
System.out.println("Expected "+from+", got "+rounded);
}
Expected 536870911, got 536870912