Java:如何执行向-Infinity而不是0舍入的整数除法? [英] Java: How do I perform integer division that rounds towards -Infinity rather than 0?

查看:174
本文介绍了Java:如何执行向-Infinity而不是0舍入的整数除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:与此不同其他问题因为OP从未明确指定向0或-Infinity舍入)

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

JLS 15.17.2 表示整数除法向零舍入。如果我想要 floor() - 类似于正除数的行为(我不关心负除数的行为),实现这一点的最简单方法是数值正确对于所有输入?

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 */
}

(更新:我想要一个解决方案 int long 算术。)

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

推荐答案

如果您可以使用第三方库, Guava 有: IntMath.divide(int,int,RoundingMode.FLOOR) LongMath.divide(int,int,RoundingMode.FLOOR) 。 (披露:我向Guava捐款。)

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.

这篇关于Java:如何执行向-Infinity而不是0舍入的整数除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆