Code review request for 6908131 Pure Java implementations of StrictMath.floor(double) &StrictMath.ceil(double)

Jeff Hain jeffhain at rocketmail.com
Wed Jan 20 21:01:11 UTC 2010


Hello.

I happen to already have developped some pure Java version of ceil(double) and floor(double).
It looks faster to me. But maybe is it incorrect ? (it's tested, but I'm never sure)
Here it is :

public class FloorCeil {
    private static final double TWO_POW_26 = Double.longBitsToDouble(0x4190000000000000L);
    private static final double TWO_POW_N26 = Double.longBitsToDouble(0x3E50000000000000L);
    private static final double TWO_POW_52 = Double.longBitsToDouble(0x4330000000000000L);
    public static double floor(double value) {
        // Faster than to work directly on bits.
        if (Math.abs(value) <= (double)Integer.MAX_VALUE) {
            if (value > 0.0) {
                return (double)(int)value;
            } else if (value < 0.0) {
                double anteComaDigits = (double)(int)value;
                if (value != anteComaDigits) {
                    return anteComaDigits - 1.0;
                } else {
                    return anteComaDigits;
                }
            } else { // value is +-0.0 (not NaN due to test against Integer.MAX_VALUE)
                return value;
            }
        } else if (Math.abs(value) < TWO_POW_52) {
            // We split the value in two:
            // high part, which is a mathematical integer,
            // and the rest, for which we can get rid of the
            // post coma digits by casting into an int.
            double highPart = ((int)(value * TWO_POW_N26)) * TWO_POW_26;
            if (value > 0.0) {
                return highPart + (double)((int)(value - highPart));
            } else {
                double anteComaDigits = highPart + (double)((int)(value - highPart));
                if (value != anteComaDigits) {
                    return anteComaDigits - 1.0;
                } else {
                    return anteComaDigits;
                }
            }
        } else { // abs(value) >= 2^52, or value is NaN
            return value;
        }
    }
    public static double ceil(double value) {
        return -floor(-value);
    }
}


Jeff


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/core-libs-dev/attachments/20100120/d8cdf6e3/attachment.html>


More information about the core-libs-dev mailing list