std::frexp, std::frexpf, std::frexpl

来自cppreference.com
< cpp‎ | numeric‎ | math
 
 
 
 
在标头 <cmath> 定义
(1)
float       frexp (float num, int* exp );

double      frexp (double num, int* exp );

longdouble frexp (longdouble 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)
longdouble frexpl(longdouble 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) 分解给定的浮点数 x 为正规化小数和二的整数指数。标准库提供所有以无 cv 限定的浮点数类型作为参数 num 的类型的 std::frexp 重载。(C++23 起)
A) 为所有整数类型提供额外重载,将它们当做 double
(C++11 起)

目录

[编辑]参数

num - 浮点数或整数
exp - 指向要存储指数到的整数的指针

[编辑]返回值

如果 num 为零,那么返回零并将零存储到 *exp

否则(如果 num 非零)如果没有发生错误,那么返回范围 (-1, -0.5], [0.5, 1) 中满足 x×2(*exp)
=num
的值 x 和存储到 *exp 的整数。

如果存储到 *exp 的值在 int 的范围外,那么行为未指定。

[编辑]错误处理

此函数不受制于任何指定于 math_errhandling 的错误。

如果实现支持 IEEE 浮点数算术(IEC 60559),那么

  • 如果 num 是 ±0,那么返回不修改的该值,并将 0 存储到 *exp
  • 如果 num 是 ±∞,那么返回它,并存储未指定值到 *exp
  • 如果 num 是 NaN,那么返回 NaN,并存储未指定值到 *exp
  • 不引发浮点数异常。
  • 如果 FLT_RADIX 是 2(或 2 的幂),那么返回值准确,忽略当前舍入模式

[编辑]注解

在二进制系统(其中 FLT_RADIX2)上,std::frexp 可实现为

{*exp =(value ==0)?0:(int)(1+std::logb(value));returnstd::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<<"给定数字 "<< f <<"(十六进制表示为 "<<std::hexfloat<< f <<std::defaultfloat<<"),\n";   double f3;double f2 =std::modf(f, &f3);std::cout<<"modf() 会把它拆分成 "<< f3 <<" + "<< f2 <<'\n';   int i; f2 = std::frexp(f, &i);std::cout<<"frexp() 会把它拆分成 "<< f2 <<" * 2^"<< i <<'\n';   i =std::ilogb(f);std::cout<<"logb()/ilogb() 会把它拆分成 "<< f /std::scalbn(1.0, i)<<" * "<<std::numeric_limits<double>::radix<<"^"<<std::ilogb(f)<<'\n';}

可能的输出:

给定数字 123.45(十六进制表示为 0x1.edccccccccccdp+6), modf() 会把它拆分成 123 + 0.45 frexp() 会把它拆分成 0.964453 * 2^7 logb()/ilogb() 会把它拆分成 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)
分解数为整数和小数部分
(函数)[编辑]
frexp 的 C 文档
close