在对浮点数进行比较时,当其中一个浮点数为 NaN 时,我可以让 Java 抛出异常吗?
今天我花了大约 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JVM 指令集参考明确禁止以下字节码:通过抛出异常来进行浮点数学计算,并严格指定当 NaN 是操作数时它们应该如何工作。如果有办法做到这一点,它要么要求您显式抛出 NaN 异常,要么使用自定义编译器为您插入这些检查。
一个可能有用的选择是编写一个如下所示的函数:
有了这个,您可以编写达到此效果的代码:
然后,这将执行计算并抛出错误。理想情况下,函数名称较短,不会太突兀。
瓦
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:
With this, you can write code to this effect:
This will then do the computation and throw on an error. Ideally with a short function name it won't be too obtrusive.
W
float 或 double 中的保护是使结果为 NaN 或 false。如果您想检测 NaN,最好首先防止该值,例如 0/0。当你进行除法时,检查除数是否为 0,如果是则抛出异常。您可以用辅助方法包装它以简化。
如果我知道该值只能是 0 或更大,我通常会添加一个偏差,例如
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.
If I know the value could be 0 or more only, I often add a bias like
This never produces NaN provided b >= 0. If a == 0, d == 0. The bias to use depends on the situation.