MATH_ERRNO, MATH_ERREXCEPT, math_errhandling
来自 cppreference.cn
定义于头文件 <cmath> |
||
#define MATH_ERRNO 1 |
(始于 C++11) | |
#define MATH_ERREXCEPT 2 |
(始于 C++11) | |
#define math_errhandling /*实现定义*/ |
(始于 C++11) | |
宏常量 math_errhandling
展开为一个 int 类型的表达式,该表达式等于 MATH_ERRNO
,或等于 MATH_ERREXCEPT
,或等于它们的按位或运算 (MATH_ERRNO | MATH_ERREXCEPT)。
math_errhandling
的值指示浮点运算符和函数执行的错误处理类型
常量 | 解释 |
MATH_ERREXCEPT
|
指示使用浮点异常:至少 FE_DIVBYZERO、 FE_INVALID 和 FE_OVERFLOW 定义于 <cfenv>。 |
MATH_ERRNO
|
指示浮点运算使用变量 errno 来报告错误。 |
如果实现支持 IEEE 浮点算术 (IEC 60559),则要求 math_errhandling & MATH_ERREXCEPT 为非零。
以下浮点错误条件被识别
条件 | 解释 | errno | 浮点异常 | 示例 |
---|---|---|---|---|
域错误 | 参数在运算的数学定义范围之外(每个函数的描述列出了要求的域错误) | EDOM | FE_INVALID | std::acos(2) |
极点错误 | 函数的数学结果正好是无穷大或未定义 | ERANGE | FE_DIVBYZERO | std::log(0.0), 1.0 / 0.0 |
溢出导致的范围错误 | 数学结果是有限的,但在舍入后变为无穷大,或在向下舍入后变为最大的可表示有限值 | ERANGE | FE_OVERFLOW | std::pow(DBL_MAX, 2) |
下溢导致的范围错误 | 结果非零,但在舍入后变为零,或变为亚正规数并损失精度 | ERANGE 或不变(实现定义) | FE_UNDERFLOW 或无(实现定义) | DBL_TRUE_MIN / 2 |
非精确结果 | 结果必须舍入以适应目标类型 | 不变 | FE_INEXACT 或无(未指定) | std::sqrt(2), 1.0 / 10.0 |
[编辑] 注解
FE_INEXACT 是否由数学库函数引发通常是未指定的,但可以在函数描述中显式指定(例如 std::rint 与 std::nearbyint)。
在 C++11 之前,浮点异常未被指定,任何域错误都要求 EDOM,溢出要求 ERANGE,下溢是实现定义的。
[编辑] 示例
运行此代码
#include <cerrno> #include <cfenv> #include <cmath> #include <cstring> #include <iostream> // #pragma STDC FENV_ACCESS ON int main() { std::cout << "MATH_ERRNO is " << (math_errhandling & MATH_ERRNO ? "set" : "not set") << '\n' << "MATH_ERREXCEPT is " << (math_errhandling & MATH_ERREXCEPT ? "set" : "not set") << '\n'; std::feclearexcept(FE_ALL_EXCEPT); errno = 0; std::cout << "log(0) = " << std::log(0) << '\n'; if (errno == ERANGE) std::cout << "errno = ERANGE (" << std::strerror(errno) << ")\n"; if (std::fetestexcept(FE_DIVBYZERO)) std::cout << "FE_DIVBYZERO (pole error) reported\n"; }
可能的输出
MATH_ERRNO is set MATH_ERREXCEPT is set log(0) = -inf errno = ERANGE (Numerical result out of range) FE_DIVBYZERO (pole error) reported
[编辑] 参见
浮点异常 (宏常量) | |
宏,展开为 POSIX 兼容的线程局部错误编号变量 (宏变量) | |
C 文档 关于 math_errhandling
|