java - 为什么除以两个整数的对数算法在某些特殊测试用例中失败?

标签 java math

我尝试使用公式 a/b = e^(ln a - ln b) 来解决臭名昭著的 Divide 2 Integers 而没有使用/% * 的问题,但是对于某些测试用例 (dividend=Integer.MAX_VALUE or MIN_VALUE and divisor=1) 我的解决方案失败了。

为什么会失败?

[编辑]:我得到的那个测试用例的答案是(MAX-1 or MIN+1)。我想知道为什么会这样。

public int divide(int dividend, int divisor) {
    boolean neg = false;
    if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0))
        neg = true;

    long a = dividend;
    a = Math.abs(a);
    long b = divisor;
    b = Math.abs(b);

    double res = Math.pow(Math.E, Math.log(a) - Math.log(b));
    int ans = Math.floor(res);
    return neg ? -ans : ans;
}

最佳答案

这里问题的根源在于计算的中间结果。

Double 是一种浮点类型,当您使用它时,您可能会失去精度

您在中间计算中使用了 double:

double res = Math.pow(Math.E, Math.log(a) - Math.log(b));
int ans = Math.floor(res);

例如,如果您使用 5 和 1,res = 4.999999999999,Math.floor(res) 将返回 4。

使用 Integer.MAX_VALUE 你有 2147483647(原始值),但结果是 2147483646。原因与 5 完全相同。

关于java - 为什么除以两个整数的对数算法在某些特殊测试用例中失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14419798/

相关文章:

java - H2 数据库未通过命令行启动

java - 为什么 SingleColumnValueFilter 不在 < 和 > 运算符上返回真实答案?

Java使用Saxon(s9api)转换XML : How to add input files in resources?

java - Libgdx - Actor 的位置不正确

mysql - 在 MySQL 中操作字段的最有效方法是什么?

java - 定义简单的数学函数并评估结果

java - Webdriver - HTTP 身份验证对话框

java - 读取具有不同名称但类型相同的元素列表

c - C 中 % 运算符的问题

C#:如何将整数四舍五入到最接近的 1000