std::frexp, std::frexpf, std::frexpl
来自 cppreference.cn
定义于头文件 <cmath> |
||
(1) | ||
float frexp ( float num, int* exp ); double frexp ( double num, int* exp ); |
(直至 C++23) | |
constexpr /* floating-point-type */ frexp ( /* floating-point-type */ num, int* exp ); |
(C++23 起) | |
float frexpf( float num, int* exp ); |
(2) | (C++11 起) (自 C++23 起为 constexpr) |
long double frexpl( long double num, int* exp ); |
(3) | (C++11 起) (自 C++23 起为 constexpr) |
额外重载 (自 C++11 起) |
||
定义于头文件 <cmath> |
||
template< class Integer > double frexp ( Integer num, int* exp ); |
(A) | (自 C++23 起为 constexpr) |
1-3) 将给定的浮点值 num 分解为规范化小数和 2 的整数指数。 库为所有 cv-不限定的浮点类型(作为参数 num 的类型)提供了
std::frexp
的重载。(C++23 起)
A) 为所有整数类型提供了额外的重载,它们被视为 double。
|
(C++11 起) |
目录 |
[编辑] 参数
num | - | 浮点值或整数值 |
exp | - | 指向存储指数的整数值的指针 |
[编辑] 返回值
如果 num 为零,返回零并将零存储到 *exp 中。
否则(如果 num 不为零),如果没有错误发生,返回范围 (-1, -0.5], [0.5, 1)
内的值 x,并将一个整数值存储到 *exp 中,使得 x×2(*exp)
== num。
如果存储到 *exp 中的值超出 int 的范围,则行为未定义。
[编辑] 错误处理
此函数不受 math_errhandling 中指定的任何错误的影响。
如果实现支持 IEEE 浮点运算 (IEC 60559),
- 如果 num 是 ±0,则原样返回,且 0 存储到 *exp 中。
- 如果 num 是 ±∞,则返回,且未指定值存储到 *exp 中。
- 如果 num 是 NaN,则返回 NaN,且未指定值存储到 *exp 中。
- 不引发浮点异常。
- 如果 FLT_RADIX 是 2(或 2 的幂),则返回的值是精确的,当前的舍入模式被忽略。
[编辑] 注意
在二进制系统上(其中 FLT_RADIX 是 2),std::frexp
可以实现为
{ *exp = (value == 0) ? 0 : (int)(1 + std::logb(value)); return std::scalbn(value, -(*exp)); }
函数 std::frexp
及其对偶 std::ldexp 可以用于操作浮点数的表示而无需直接位操作。
不需要完全按照 (A) 提供额外的重载。它们只需要足以确保对于整数类型的参数 num,std::frexp(num, exp) 具有与 std::frexp(static_cast<double>(num), exp) 相同的效果。
[编辑] 示例
比较不同的浮点分解函数
运行此代码
#include <cmath> #include <iostream> #include <limits> 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'; }
可能的输出
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
[编辑] 参阅
(C++11)(C++11) |
将数字乘以 2 的整数次幂 (函数) |
(C++11)(C++11)(C++11) |
提取数字的指数 (函数) |
(C++11)(C++11)(C++11) |
提取数字的指数 (函数) |
(C++11)(C++11) |
将数字分解为整数部分和小数部分 (函数) |
C 文档 为 frexp
|