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 since C++23) |
long double ldexpl( long double num, int exp ); |
(3) | (C++11 起) (constexpr since C++23) |
额外重载 (自 C++11 起) |
||
定义于头文件 <cmath> |
||
template< class Integer > double ldexp ( Integer num, int exp ); |
(A) | (C++11 起) (constexpr since C++23) |
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_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
|