C++:在数学错误中创建实际错误而不是 NAN

c++: create actual error in math errors instead of nan

本文关键字:错误 NAN C++ 创建      更新时间:2023-10-16

我有一个非常大的代码,很难调试。 在某些情况下,它会为结果提供nan

我知道它可能是在像sqrt(-1)这样的数学错误中产生的,但我无法发现错误。如果我能在数学错误中产生错误,而不是nan,我就能很容易地发现错误。

我可以通过定义宏来实现这一点吗? 我想我在某处看到了这样的解决方案。

注意:我不想在每次数学运算后都使用if(isnan(res)) exit(0);

感谢克里斯,这里是数学错误处理的夏天。

这些浮点异常定义在头文件中cfenvFE_ALL_EXCEPTFE_DIVBYZEROFE_INEXACTFE_INVALIDFE_OVERFLOWFE_UNDERFLOW。 名称是不言自明的。

我们可以确定当前使用 fetestex 例外设置了浮点异常的指定子集。 我们可以使用 FeclearExclude 清除已发生的异常列表。

下面是一个代码,它显示了我们如何确定引发的浮点异常:

C++11标准:

#include <iostream>
#include <cfenv>
#include <cmath>
#pragma STDC FENV_ACCESS ON
volatile double zero = 0.0; // volatile not needed where FENV_ACCESS is supported
volatile double one = 1.0;  // volatile not needed where FENV_ACCESS is supported
int main()
{
std::feclearexcept(FE_ALL_EXCEPT);
std::cout <<  "1.0/0.0 = " << 1.0 / zero << 'n';
if(std::fetestexcept(FE_DIVBYZERO)) {
std::cout << "division by zero reportedn";
} else {
std::cout << "divsion by zero not reportedn";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "1.0/10 = " << one/10 << 'n';
if(std::fetestexcept(FE_INEXACT)) {
std::cout << "inexact result reportedn";
} else {
std::cout << "inexact result not reportedn";
}
std::feclearexcept(FE_ALL_EXCEPT);
std::cout << "sqrt(-1) = " << std::sqrt(-1) << 'n';
if(std::fetestexcept(FE_INVALID)) {
std::cout << "invalid result reportedn";
} else {
std::cout << "invalid result not reportedn";
}
}

在C99中:

#include <stdio.h>
#include <math.h>
#include <float.h>//for DBL_MIN and DBL_MAX
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
printf("exceptions raised:");
if(fetestexcept(FE_DIVBYZERO)) printf(" FE_DIVBYZERO");
if(fetestexcept(FE_INEXACT))   printf(" FE_INEXACT");
if(fetestexcept(FE_INVALID))   printf(" FE_INVALID");
if(fetestexcept(FE_OVERFLOW))  printf(" FE_OVERFLOW");
if(fetestexcept(FE_UNDERFLOW)) printf(" FE_UNDERFLOW");
feclearexcept(FE_ALL_EXCEPT);
printf("n");
}
int main(void)
{
printf("MATH_ERREXCEPT is %sn",
math_errhandling & MATH_ERREXCEPT ? "set" : "not set");
printf("0.0/0.0 = %fn", 0.0/0.0);
show_fe_exceptions();
printf("1.0/0.0 = %fn", 1.0/0.0);
show_fe_exceptions();
printf("1.0/10.0 = %fn", 1.0/10.0);
show_fe_exceptions();
printf("sqrt(-1) = %fn", sqrt(-1));
show_fe_exceptions();
printf("DBL_MAX*2.0 = %fn", DBL_MAX*2.0);
show_fe_exceptions();
printf("nextafter(DBL_MIN/pow(2.0,52),0.0) = %.1fn",
nextafter(DBL_MIN/pow(2.0,52),0.0));
show_fe_exceptions();
}