std::ldexp, std::ldexpf, std::ldexpl

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

double      ldexp (double num, int exp );

longdouble ldexp (longdouble num, int exp );
(C++23 前)
constexpr/* floating-point-type */
            ldexp (/* floating-point-type */ num, int exp );
(C++23 起)
float       ldexpf(float num, int exp );
(2) (C++11 起)
(C++23 起为 constexpr)
longdouble ldexpl(longdouble num, int exp );
(3) (C++11 起)
(C++23 起为 constexpr)
额外重载(C++11 起)
在标头 <cmath> 定义
template<class Integer >
double      ldexp ( Integer num, int exp );
(A) (C++11 起)
(C++23 起为 constexpr)
1-3) 将浮点数 num 乘以 2 的 exp 次幂。标准库提供所有以无 cv 限定的浮点数类型作为实参 num 的类型的 std::ldexp 重载。(C++23 起)
A) 为所有整数类型提供额外重载,将它们当做 double
(C++11 起)

目录

[编辑]参数

num - 浮点数或整数
exp - 整数

[编辑]返回值

如果没有发生错误,那么返回 num 乘 2 的 exp 次幂(num×2exp
)。

如果发生上溢导致的值域错误,那么返回 ±HUGE_VAL±HUGE_VALF±HUGE_VALL

如果发生下溢导致的值域错误,那么返回(舍入后的)正确结果。

[编辑]错误处理

报告 math_errhandling 中指定的错误。

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

  • 决不引发 FE_INEXACT,除非出现值域错误(结果准确)
  • 忽略当前舍入模式,除非出现值域错误
  • 如果 num 是 ±0,那么返回不修改的该值
  • 如果 num 是 ±∞,那么返回不修改的该值
  • 如果 exp 是 0,那么返回不修改的 num
  • 如果 num 是 NaN,那么返回 NaN

[编辑]注解

在二进制系统上(其中 FLT_RADIX2),std::ldexp 等价于 std::scalbn

函数 std::ldexp(“加载指数”)与它的对偶 std::frexp 能一同用于操纵浮点数的表示,而无需直接进行位操作。

多数实现上,std::ldexp 效率低于用通常算术运算符乘或除以二的幂。

额外重载不需要以 (A) 的形式提供。它们只需要能够对它们的整数类型实参 num 确保 std::ldexp(num, exp)std::ldexp(static_cast<double>(num), exp) 的效果相同。

对于 2 的浮点数指数次幂,可以使用 std::exp2

[编辑]示例

#include <cerrno>#include <cfenv>#include <cmath>#include <cstring>#include <iostream>// #pragma STDC FENV_ACCESS ON   int main(){std::cout<<"ldexp(5, 3) = 5 * 8 = "<< std::ldexp(5, 3)<<'\n'<<"ldexp(7, -4) = 7 / 16 = "<< std::ldexp(7, -4)<<'\n'<<"ldexp(1, -1074) = "<< std::ldexp(1, -1074)<<"(最小的正次正规 float64_t)\n"<<"ldexp(nextafter(1,0), 1024) = "<< std::ldexp(std::nextafter(1,0), 1024)<<"(最大的有限 float64_t)\n";   // 特殊值std::cout<<"ldexp(-0, 10) = "<< std::ldexp(-0.0, 10)<<'\n'<<"ldexp(-Inf, -1) = "<< std::ldexp(-INFINITY, -1)<<'\n';   // 错误处理std::feclearexcept(FE_ALL_EXCEPT);errno=0;constdouble inf = std::ldexp(1, 1024);constbool is_range_error =errno==ERANGE;   std::cout<<"ldexp(1, 1024) = "<< inf <<'\n';if(is_range_error)std::cout<<" errno == ERANGE: "<<std::strerror(ERANGE)<<'\n';if(std::fetestexcept(FE_OVERFLOW))std::cout<<" 发生 FE_OVERFLOW\n";}

可能的输出:

ldexp(5, 3) = 5 * 8 = 40 ldexp(7, -4) = 7 / 16 = 0.4375 ldexp(1, -1074) = 4.94066e-324(最小的正次正规 float64_t) ldexp(nextafter(1,0), 1024) = 1.79769e+308(最大的有限 float64_t) ldexp(-0, 10) = -0 ldexp(-Inf, -1) = -inf ldexp(1, 1024) = inf errno == ERANGE: Numerical result out of range 发生 FE_OVERFLOW

[编辑]参阅

(C++11)(C++11)
将数分解为有效数字和以 2 为底的指数
(函数)[编辑]
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)
将数乘以 FLT_RADIX 的幂次
(函数)[编辑]
(C++11)(C++11)(C++11)
返回 2 的给定次幂(2x
(函数)[编辑]
ldexp 的 C 文档
close