std::ldexp, std::ldexpf, std::ldexpl
來自 cppreference.com
定義於標頭檔案 <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
|