在对浮点数进行比较时,当其中一个浮点数为 NaN 时,我可以让 Java 抛出异常吗?

发布于 2024-10-17 14:24:26 字数 101 浏览 2 评论 0原文

今天我花了大约 2 个小时来追踪一个错误,如果 java 在比较 NaN 与浮点数时抛出异常,我会发现速度要快得多。如果我将来能够保护自己免受这种情况的侵害,那就太好了。任何帮助表示赞赏。

I spent about 2 hours tracking down a bug today and I would've found it much quicker had java thrown an exception when comparing NaN with a float. It would be nice if I could protect myself from this in the future. Any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野生奥特曼 2024-10-24 14:24:26

JVM 指令集参考明确禁止以下字节码:通过抛出异常来进行浮点数学计算,并严格指定当 NaN 是操作数时它们应该如何工作。如果有办法做到这一点,它要么要求您显式抛出 NaN 异常,要么使用自定义编译器为您插入这些检查。

一个可能有用的选择是编写一个如下所示的函数:

public static float check(float value) {
    if (Float.isNaN(value))
        throw new ArithmeticException("NaN");
    return value;
}

有了这个,您可以编写达到此效果的代码:

float f = check(myOtherFloat / yetAnotherFloat);

然后,这将执行计算并抛出错误。理想情况下,函数名称较短,不会太突兀。

The JVM instruction set reference specifically disallows the byte codes that do floating point math from throwing exceptions and rigidly specifies how they should work when NaN is an operand. If there is a way to do this, it will either require you to explicitly throw exceptions on NaN or to use a custom compiler to insert these checks for you.

One option that might be helpful would be to write a function like this:

public static float check(float value) {
    if (Float.isNaN(value))
        throw new ArithmeticException("NaN");
    return value;
}

With this, you can write code to this effect:

float f = check(myOtherFloat / yetAnotherFloat);

This will then do the computation and throw on an error. Ideally with a short function name it won't be too obtrusive.

W

萌酱 2024-10-24 14:24:26

float 或 double 中的保护是使结果为 NaN 或 false。如果您想检测 NaN,最好首先防止该值,例如 0/0。当你进行除法时,检查除数是否为 0,如果是则抛出异常。您可以用辅助方法包装它以简化。

public static double div(double a, double b) {
    if(b == 0) throw new IllegalArguementException();
    return a / b;
}

如果我知道该值只能是 0 或更大,我通常会添加一个偏差,例如

double d = a / (b + 1e-9);

This never Produce NaNprovid b >= 0. If a == 0, d == 0. 使用的偏差取决于具体情况。

The protection in float or double is to make the result NaN or false. If you want to detect NaN, you are better of preventing the value in the first place e.g 0/0. When you do a division, check for 0 as a divisor and throw an Exception if it is. You can wrap this with a helper method to simplify.

public static double div(double a, double b) {
    if(b == 0) throw new IllegalArguementException();
    return a / b;
}

If I know the value could be 0 or more only, I often add a bias like

double d = a / (b + 1e-9);

This never produces NaN provided b >= 0. If a == 0, d == 0. The bias to use depends on the situation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文