std:: ldexp, std:: ldexpf, std:: ldexpl
|
定义于头文件
<cmath>
|
||
| (1) | ||
|
float
ldexp
(
float
num,
int
exp
)
;
double
ldexp
(
double
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) |
|
long
double
ldexpl
(
long
double
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) |
std::ldexp
的重载,作为参数
num
的类型。
(C++23 起)
|
A)
为所有整数类型提供了额外的重载,这些类型被视为
double
。
|
(since C++11) |
目录 |
参数
| num | - | 浮点数或整数值 |
| exp | - | 整数值 |
返回值
如果未发生错误,将返回
num
乘以 2 的
exp
次方(
num×2
exp
)。
如果发生因溢出导致的范围错误,将返回
±HUGE_VAL
、
±HUGE_VALF
或
±HUGE_VALL
。
如果发生因下溢导致的范围错误,将返回正确结果(经舍入后)。
错误处理
错误报告方式遵循 math_errhandling 中的规范。
如果实现支持 IEEE 浮点算术 (IEC 60559),
- 除非发生范围错误,否则永远不会引发 FE_INEXACT (结果是精确的)。
- 除非发生范围错误,否则将忽略 当前舍入模式 。
- 如果 num 为 ±0,则直接返回该值(不作修改)。
- 如果 num 为 ±∞,则直接返回该值(不作修改)。
- 如果 exp 为 0,则直接返回 num (不作修改)。
- 如果 num 为 NaN,则返回 NaN。
注释
在二进制系统(其中
FLT_RADIX
为
2
)上,
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; const double inf = std::ldexp(1, 1024); const bool 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: 数值结果超出范围
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
的指定次幂(
2
x
)
(函数) |
|
C 文档
for
ldexp
|
|