C++ 中 NaN 的原因不引发浮点异常的应用程序
为了找到浮点变量在我的 C++ 程序中设置为 NaN 的原因,我启用了如下浮点异常:
#include <fenv.h>
feenableexcept(FE_INVALID | FE_OVERFLOW);
我知道它有效,因为当我写:
int val = 0.0/0.0;
在我的程序中会出现浮点异常。 但是 NaN 正在通过我的程序的浮点计算“传播”,我不知道哪个变量首先设置为 NaN。
存在哪些原因导致变量被设置为 NaN,但不会导致浮点异常?
To find the cause of floating point variables beeing set to NaN in my C++ program I enabled floating point exceptions like this:
#include <fenv.h>
feenableexcept(FE_INVALID | FE_OVERFLOW);
I know it works because when I write:
int val = 0.0/0.0;
in my program a floating point exception is risen.
But NaNs are "spreading" through the floating point calculations of my program and I have no idea which variable is set to NaN first.
What causes for a variable beeing set to NaN exist, that would not cause a floating point exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果任何输入具有安静的 NaN 值,它将导致几乎所有消耗该输入的浮点运算的结果为 NaN 而不会引发无效异常。
最可能的解释是,某些数据是从错误的地址读取的,并且读取的数据(甚至可能不是浮点数据)恰好与安静的 NaN 编码匹配。这种情况很容易发生,因为相对常见的模式
0xffff...
编码一个安静的 NaN。If any input has a quiet NaN value, it will cause the result of nearly any floating-point operation that consumes it to be NaN without raising the invalid exception.
The most likely explanation is that some data is being read from the wrong address, and that the read data (which may not even be floating-point data) happens to match a quiet NaN encoding. This can happen pretty easily, because the relatively common pattern
0xffff...
encodes a quiet NaN.你在做平方根运算吗?如果您尝试计算负数的平方根(如 sqrt(-1) 所示),那么您将得到 Nan。在这种情况下,您应该会收到“无效操作”异常。您确定正确捕获了所有异常吗?看起来数字异常没有被捕获在代码中的某个地方。
Are you doing any square root operation? If you try to compute a square root for a negative number as in sqrt(-1) then you will get a Nan. In this case you should get an 'Invalid Operation' exception though. Are you sure you are trapping correctly all exceptions? It seems like a numeric exception is untrapped somewhere in your code.