c - 使用 Infinity 和 NaN 禁用异常

标签 c nan infinity math.h

我有一个巨大的项目(不是我构建的),允许具有 InfinityNaN 值。虽然这是允许的,但这是不可取的。我read这些值是由此类操作生成的:

1/0 = ∞
log (0) = -∞
sqrt (-1) = NaN

除此之外,当达到它们时,应该抛出 FP 异常

如果我的项目允许使用 NaNInfinity 进行操作,我认为 SIGFPE 会在某个地方处理,但我搜索了整个项目但找不到它。

还有其他方法可以禁用此异常吗?我的目标是能够检测到此类值的第一次出现。

编辑: 我使用的是 Windows,我打算启用该信号,但在启用之前,我想了解它是否被禁用。

最佳答案

我认为您不会遇到您所谈论的问题。默认情况下,不会引发 FP 异常。从 Windows documentation :

By default, the system has all FP exceptions turned off. Therefore, computations result in NAN or INFINITY, rather than an exception. Before you can trap floating-point (FP) exceptions using structured exception handling, you must call the _controlfp_s C run-time library function to turn on all possible FP exceptions. To trap only particular exceptions, use only the flags that correspond to the exceptions to be trapped. Note that any handler for FP errors should call _clearfp as its first FP instruction. This function clears floating-point exceptions.

GCC 也是如此,其中 documentation说:

When exceptions occur (when exceptions are raised, in the language of the standard), one of two things can happen. By default the exception is simply noted in the floating-point status word, and the program continues as if nothing had happened. The operation produces a default value, which depends on the exception [...]). Your program can check the status word to find out which exceptions happened.

要在 Windows 环境中启用异常(这将停止程序的执行),您可以尝试类似的操作

#include <float.h>

int main() {
    _clearfp();
    unsigned int current_word = 0;
    _controlfp_s(&current_word, ~_EM_ZERODIVIDE, _MCW_EM);
    double div = 0.;
    double f = 1. / div;
}

对于非阻塞解决方案,请尝试使用 fenv.h,如所述 here在 cppreference.com 上。

关于c - 使用 Infinity 和 NaN 禁用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53225506/

相关文章:

c - 从文件中的行读取最大单词时重复标记?

c++ - 我可以在没有 Visual Studio 的情况下使用 Visual C++ 编译器吗?

c - 如何对嵌套在结构体数组中的结构体数组进行排序 C

C++ 编译器为 AVX SIMD 代码中从自身减去 +-Infinity 或 +-NaN 的恒定传播给出不同的 NaN 符号

java - 如何在Piccolo2D中制作无限(无限)节点?

r - 为什么 NA_real_ <= Inf 返回 NA?

json - (+/-) JSON 导入中的无穷大

编程ic时编译器错误

python - 在忽略 NaN 的同时连接 pandas DataFrame 中的列值

python - 拉伸(stretch)数组并填充 nan