std::logb, std::logbf, std::logbl
来自 cppreference.cn
定义于头文件 <cmath> |
||
(1) | ||
float logb ( float num ); double logb ( double num ); |
(直到 C++23) | |
constexpr /*floating-point-type*/ logb ( /*floating-point-type*/ num ); |
(自 C++23 起) | |
float logbf( float num ); |
(2) | (自 C++11 起) (constexpr 自 C++23 起) |
long double logbl( long double num ); |
(3) | (自 C++11 起) (constexpr 自 C++23 起) |
SIMD 重载 (自 C++26 起) |
||
定义于头文件 <simd> |
||
template< /*math-floating-point*/ V > constexpr /*deduced-simd-t*/<V> |
(S) | (自 C++26 起) |
附加重载 (自 C++11 起) |
||
定义于头文件 <cmath> |
||
template< class Integer > double logb ( Integer num ); |
(A) | (constexpr 自 C++23 起) |
1-3) 从浮点参数 num 中提取无偏的、与基数无关的指数值,并将其作为浮点值返回。 库为所有 cv 限定的浮点类型提供
std::logb
的重载作为参数类型。(自 C++23 起)
S) SIMD 重载对 v_num 执行元素级的
std::logb 。
|
(自 C++26 起) |
A) 为所有整数类型提供了额外的重载,它们被视为 double。
|
(自 C++11 起) |
形式上,对于非零的 num,无偏指数是 logr|num| 的有符号整数部分(由此函数作为浮点值返回),其中 r 是 std::numeric_limits<T>::radix,而 T
是 num 的浮点类型。如果 num 是次正规的,则将其视为已正规化。
内容 |
[编辑] 参数
num | - | 浮点值或整数值 |
[编辑] 返回值
如果没有错误发生,则 num 的无偏指数将作为有符号浮点值返回。
如果发生域错误,则返回实现定义的值。
如果发生极点错误,则返回 -HUGE_VAL、-HUGE_VALF
或 -HUGE_VALL
。
[编辑] 错误处理
错误将按照 math_errhandling 中的规定报告。
如果 num 为零,则可能发生域或范围错误。
如果实现支持 IEEE 浮点算术 (IEC 60559),
- 如果 num 为 ±0,则返回 -∞ 并引发 FE_DIVBYZERO。
- 如果 num 为 ±∞,则返回 +∞。
- 如果 num 为 NaN,则返回 NaN。
- 在所有其他情况下,结果都是精确的(永远不会引发 FE_INEXACT),并且 当前的舍入模式 将被忽略。
[编辑] 注解
POSIX 要求,如果 num 为 ±0,则会发生极点错误。
std::logb
返回的指数值始终比 std::frexp 返回的指数值小 1,这是因为归一化要求不同:对于 std::logb
返回的指数 e,|num*r-e
| 介于 1 和 r 之间(通常介于 1 和 2 之间),但对于 std::frexp 返回的指数 e,|num*2-e
| 介于 0.5 和 1 之间。
不需要完全按照 (A) 中的形式提供附加重载。它们只需要足以确保对于整数类型的参数 num,std::logb(num) 具有与 std::logb(static_cast<double>(num)) 相同的效果。
[编辑] 示例
比较不同的浮点分解函数
运行此代码
#include <cfenv> #include <cmath> #include <iostream> #include <limits> // #pragma STDC FENV_ACCESS ON int main() { double f = 123.45; std::cout << "Given the number " << f << " or " << std::hexfloat << f << std::defaultfloat << " in hex,\n"; double f3; double f2 = std::modf(f, &f3); std::cout << "modf() makes " << f3 << " + " << f2 << '\n'; int i; f2 = std::frexp(f, &i); std::cout << "frexp() makes " << f2 << " * 2^" << i << '\n'; i = std::ilogb(f); std::cout << "logb()/ilogb() make " << f / std::scalbn(1.0, i) << " * " << std::numeric_limits<double>::radix << "^" << std::ilogb(f) << '\n'; // error handling std::feclearexcept(FE_ALL_EXCEPT); std::cout << "logb(0) = " << std::logb(0) << '\n'; if (std::fetestexcept(FE_DIVBYZERO)) std::cout << " FE_DIVBYZERO raised\n"; }
可能的输出
Given the number 123.45 or 0x1.edccccccccccdp+6 in hex, modf() makes 123 + 0.45 frexp() makes 0.964453 * 2^7 logb()/ilogb() make 1.92891 * 2^6 logb(0) = -Inf FE_DIVBYZERO raised
[编辑] 参见
(C++11)(C++11) |
将数字分解为尾数和以 2 为底的指数 (函数) |
(C++11)(C++11)(C++11) |
提取数字的指数 (函数) |
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) |
将数字乘以 FLT_RADIX 的幂 (函数) |
C 文档 关于 logb
|