Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How do I perform integer division that rounds towards -Infinity rather than 0?

(note: not the same as this other question since the OP never explicitly specified rounding towards 0 or -Infinity)

JLS 15.17.2 says that integer division rounds towards zero. If I want floor()-like behavior for positive divisors (I don't care about the behavior for negative divisors), what's the simplest way to achieve this that is numerically correct for all inputs?

int ifloor(int n, int d)
{
    /* returns q such that n = d*q + r where 0 <= r < d
     * for all integer n, d where d > 0
     *
     * d = 0 should have the same behavior as `n/d`
     *
     * nice-to-have behaviors for d < 0:
     *   option (a). same as above: 
     *     returns q such that n = d*q + r where 0 <= r < -d
     *   option (b). rounds towards +infinity:
     *     returns q such that n = d*q + r where d < r <= 0
     */
}

long lfloor(long n, long d)
{
    /* same behavior as ifloor, except for long integers */
}

(update: I want to have a solution both for int and long arithmetic.)

like image 605
Jason S Avatar asked May 04 '12 23:05

Jason S


People also ask

How do you round up in integer division?

If the divisor and dividend have the same sign then the result is zero or positive. If the divisor and dividend have opposite signs then the result is zero or negative. If the division is inexact then the quotient is rounded up.

Does integer division round up in Java?

Java does a round down in case of division of two integer numbers.

How does Java handle division by zero?

Values like INFINITY and NaN are available for floating-point numbers but not for integers. As a result, dividing an integer by zero will result in an exception. However, for a float or double, Java allows the operation.


1 Answers

If you can use third-party libraries, Guava has this: IntMath.divide(int, int, RoundingMode.FLOOR) and LongMath.divide(int, int, RoundingMode.FLOOR). (Disclosure: I contribute to Guava.)

If you don't want to use a third-party library for this, you can still look at the implementation.

like image 184
Louis Wasserman Avatar answered Sep 27 '22 16:09

Louis Wasserman