ldexp, ldexpf, ldexpl

< c‎ | numeric‎ | math
在标头 <math.h> 定义
float       ldexpf( float arg, int exp );
(1) (C99 起)
double      ldexp( double arg, int exp );
(2)
long double ldexpl( long double arg, int exp );
(3) (C99 起)
在标头 <tgmath.h> 定义
#define ldexp( arg, exp )
(4) (C99 起)
1-3) 将浮点值 arg 乘以 2exp 次幂。
4) 泛型宏:若 arg 拥有 long double 类型,则调用 ldexpl。否则,若 arg 拥有整数类型或 double 类型,则调用 ldexp。否则调用 ldexpf

参数

arg - 浮点值
exp - 整数值

返回值

若不出现错误,则返回 arg 乘 2 的 exp 次幂(arg×2exp
)。

若出现上溢所致的值域错误,则返回 ±HUGE_VAL±HUGE_VALF±HUGE_VALL

若出现下溢所致的值域错误,则返回(舍入后的)正确结果。

错误处理

报告 math_errhandling 中指定的错误。

若实现支持 IEEE 浮点算术(IEC 60559),则

  • 决不引发 FE_INEXACT,除非出现值域错误(结果准确)
  • 忽略当前舍入模式,除非出现值域错误
  • arg 为 ±0,则返回不修改的参数
  • arg 为 ±∞,则返回不修改的参数
  • exp 为 0,则返回不修改的 arg
  • arg 为 NaN,则返回 NaN

注解

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

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

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

示例

#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
// #pragma STDC FENV_ACCESS ON
 
int main(void)
{
    printf("ldexp(7, -4) = %f\n", ldexp(7, -4));
    printf("ldexp(1, -1074) = %g (double 的最小非正规正值)\n",
            ldexp(1, -1074));
    printf("ldexp(nextafter(1,0), 1024) = %g (double 的最大有限值)\n",
            ldexp(nextafter(1,0), 1024));
    // 特殊值
    printf("ldexp(-0, 10) = %f\n", ldexp(-0.0, 10));
    printf("ldexp(-Inf, -1) = %f\n", ldexp(-INFINITY, -1));
 
    // 错误处理
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("ldexp(1, 1024) = %f\n", ldexp(1, 1024));
    if (errno == ERANGE)
        perror("    errno == ERANGE");
    if (fetestexcept(FE_OVERFLOW))
        puts("    FE_OVERFLOW raised");
}

可能的输出:

ldexp(7, -4) = 0.437500
ldexp(1, -1074) = 4.94066e-324 (double 的最小非正规正值)
ldexp(nextafter(1,0), 1024) = 1.79769e+308 (double 的最大有限值)
ldexp(-0, 10) = -0.000000
ldexp(-Inf, -1) = -inf
ldexp(1, 1024) = inf
    errno == ERANGE: Numerical result out of range
    FE_OVERFLOW raised

引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.12.6.6 The ldexp functions (第 TBD 页)
  • 7.25 Type-generic math <tgmath.h> (第 TBD 页)
  • F.10.3.6 The ldexp functions (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.12.6.6 The ldexp functions (第 TBD 页)
  • 7.25 Type-generic math <tgmath.h> (第 TBD 页)
  • F.10.3.6 The ldexp functions (第 TBD 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.12.6.6 The ldexp functions (第 244 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.3.6 The ldexp functions (第 522 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.12.6.6 The ldexp functions (第 225 页)
  • 7.22 Type-generic math <tgmath.h> (第 335-337 页)
  • F.9.3.6 The ldexp functions (第 459 页)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.5.4.3 The ldexp function

参阅

(C99)(C99)
将数拆分成有效数字和 2 的幂次
(函数)
(C99)(C99)(C99)(C99)(C99)(C99)
高效计算一个数乘 FLT_RADIX 的幂
(函数)