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 /* 浮点类型 */ frexp ( /* 浮点类型 */ num, int* exp ); |
(C++23 起) | |
float frexpf( float num, int* exp ); |
(2) | (C++11 起) (constexpr C++23 起) |
long double frexpl( long double num, int* exp ); |
(3) | (C++11 起) (constexpr C++23 起) |
额外的重载 (C++11 起) |
||
在头文件 <cmath> 中定义 |
||
template< class Integer > double frexp ( Integer num, int* exp ); |
(A) | (constexpr C++23 起) |
1-3) 将给定的浮点值 num 分解为归一化的小数和 2 的积分指数。 库为所有 cv 限定的浮点类型提供了
std::frexp
的重载,作为形参 num 的类型。(C++23 起)
A) 为所有整数类型提供了额外的重载,它们被视为 double。
|
(C++11 起) |
目录 |
[edit] 参数
num | - | 浮点值或整数值 |
exp | - | 指向整数值的指针,用于存储指数 |
[edit] 返回值
如果 num 为零,则返回零,并将零存储在 *exp 中。
否则(如果 num 不为零),如果没有错误发生,则返回范围 (-1, -0.5], [0.5, 1)
中的值 x,并将一个整数值存储在 *exp 中,使得 x×2(*exp)
== num。
如果要存储在 *exp 中的值超出 int 的范围,则行为未指定。
[edit] 错误处理
此函数不受 math_errhandling 中指定的任何错误的影响。
如果实现支持 IEEE 浮点算术 (IEC 60559),
- 如果 num 为 ±0,则返回它,不修改,并将 0 存储在 *exp 中。
- 如果 num 为 ±∞,则返回它,并将未指定的值存储在 *exp 中。
- 如果 num 为 NaN,则返回 NaN,并将未指定的值存储在 *exp 中。
- 不引发浮点异常。
- 如果 FLT_RADIX 为 2(或 2 的幂),则返回的值是精确的,当前的舍入模式将被忽略。
[edit] 注解
在二进制系统上(其中 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) 相同的效果。
[edit] 示例
比较不同的浮点数分解函数
运行此代码
#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
[edit] 参见
(C++11)(C++11) |
将数字乘以 2 的整数次幂 (函数) |
(C++11)(C++11)(C++11) |
提取数字的指数 (函数) |
(C++11)(C++11)(C++11) |
提取数字的指数 (函数) |
(C++11)(C++11) |
将数字分解为整数和分数部分 (函数) |
C 文档 关于 frexp
|