std::ldexp, std::ldexpf, std::ldexpl
来自 cppreference.cn
定义于头文件 <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 起) (constexpr 自 C++23 起) |
long double ldexpl( long double num, int exp ); |
(3) | (自 C++11 起) (constexpr 自 C++23 起) |
附加重载 (自 C++11 起) |
||
定义于头文件 <cmath> |
||
template< class Integer > double ldexp ( Integer num, int exp ); |
(A) | (自 C++11 起) (constexpr 自 C++23 起) |
1-3) 将浮点值 num 乘以数字 2 的 exp 次幂。 库为所有非限定 cv 浮点类型提供
std::ldexp
的重载作为参数 num 的类型。(自 C++23 起)
A) 为所有整数类型提供附加重载,它们被视为 double。
|
(自 C++11 起) |
内容 |
[编辑] 参数
num | - | 浮点值或整数值 |
exp | - | 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_RADIX 为 2),std::ldexp
等价于 std::scalbn。
函数 std::ldexp
(“load exponent”,加载指数) 及其对偶函数 std::frexp 可用于操作浮点数的表示形式,而无需直接进行位操作。
在许多实现中,std::ldexp
的效率不如使用算术运算符乘以或除以 2 的幂。
不需要完全按照 (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) << " (minimum positive subnormal float64_t)\n" << "ldexp(nextafter(1,0), 1024) = " << std::ldexp(std::nextafter(1,0), 1024) << " (largest finite float64_t)\n"; // special values std::cout << "ldexp(-0, 10) = " << std::ldexp(-0.0, 10) << '\n' << "ldexp(-Inf, -1) = " << std::ldexp(-INFINITY, -1) << '\n'; // error handling 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 raised\n"; }
可能的输出
ldexp(5, 3) = 5 * 8 = 40 ldexp(7, -4) = 7 / 16 = 0.4375 ldexp(1, -1074) = 4.94066e-324 (minimum positive subnormal float64_t) ldexp(nextafter(1,0), 1024) = 1.79769e+308 (largest finite float64_t) ldexp(-0, 10) = -0 ldexp(-Inf, -1) = -inf ldexp(1, 1024) = inf errno == ERANGE: Numerical result out of range FE_OVERFLOW raised
[编辑] 参见
(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) (函数) |
C 文档 关于 ldexp
|