Ldexp
定义于头文件 <cmath>
中。
描述
将浮点值 num
乘以 2 的 exp
次幂。
该库为所有 cv-unqualified 浮点类型提供了 std::ldexp 的重载,作为参数 num
的类型 (自 C++23 起).
额外的重载为所有整数类型提供,这些类型被视为 double (自 C++11 起).
声明
- C++23
- C++11
// 1)
constexpr /* floating-point-type */
ldexp ( /* floating-point-type */ num, int exp )
// 2)
constexpr float ldexpf( float num, int exp );
// 3)
constexpr long double ldexpl( long double num, int exp );
// 4)
template< class Integer >
constexpr double ldexp ( Integer num, int exp );
// 1)
float ldexp ( float num, int exp );
// 2)
double ldexp ( double num, int exp );
// 3)
long double ldexp ( long double num, int exp );
// 4)
float ldexpf( float num, int exp );
// 5)
long double ldexpl( long double num, int exp );
// 6)
template< class Integer >
double ldexp ( Integer num, int exp );
参数
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 的幂运算。
额外的重载不需要完全按照额外重载提供。它们只需要足以确保对于其整数类型的参数 num
,
std::ldexp(num, exp)
与 std::ldexp(static_cast<double>(num), exp)
具有相同的效果。
示例
#include <cerrno>
#include <cfenv>
#include <cmath>
#include <cstring>
#include <iostream>
// #pragma STDC FENV_ACCESS ON
int main()
{
std::cout
<< "ldexp(7, -4) = "
<< std::ldexp(7, -4) << '\n'
<< "ldexp(1, -1074) = "
<< std::ldexp(1, -1074)
<< " (minimum positive subnormal double)\n"
<< "ldexp(nextafter(1,0), 1024) = "
<< std::ldexp(std::nextafter(1,0), 1024)
<< " (largest finite double)\n";
// special values
std::cout
<< "ldexp(-0, 10) = "
<< std::ldexp(-0.0, 10) << '\n'
<< "ldexp(-Inf, -1) = "
<< std::ldexp(-INFINITY, -1) << '\n';
// error handling
errno = 0;
std::feclearexcept(FE_ALL_EXCEPT);
std::cout
<< "ldexp(1, 1024) = "
<< std::ldexp(1, 1024) << '\n';
if (errno == ERANGE)
std::cout
<< "errno == ERANGE: "
<< std::strerror(errno) << '\n';
if (std::fetestexcept(FE_OVERFLOW))
std::cout
<< "FE_OVERFLOW raised\n";
}
ldexp(7, -4) = 0.4375
ldexp(1, -1074) = 4.94066e-324 (minimum positive subnormal double)
ldexp(nextafter(1,0), 1024) = 1.79769e+308 (largest finite double)
ldexp(-0, 10) = -0
ldexp(-Inf, -1) = -inf
ldexp(1, 1024) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised