std::exp2, std::exp2f, std::exp2l
来自cppreference.com
在标头 <cmath> 定义 | ||
(1) | ||
float exp2 (float num ); double exp2 (double num ); | (C++23 前) | |
/* 浮点数类型 */ exp2 (/* 浮点数类型 */ num ); | (C++23 起) (C++26 起 constexpr) | |
float exp2f(float num ); | (2) | (C++11 起) (C++26 起为 constexpr) |
longdouble exp2l(longdouble num ); | (3) | (C++11 起) (C++26 起为 constexpr) |
SIMD 重载(C++26 起) | ||
在标头 <simd> 定义 | ||
template</*math-floating-point*/ V > constexpr/*deduced-simd-t*/<V> | (S) | (C++26 起) |
额外重载(C++11 起) | ||
在标头 <cmath> 定义 | ||
template<class Integer > double exp2 ( Integer num ); | (A) | (C++26 起为 constexpr) |
1-3) 计算 2 的给定 num 次幂。标准库提供所有以无 cv 限定的浮点数类型作为形参的类型的
std::exp2
重载。(C++23 起)S) SIMD 重载对 v_num 实施逐元素 std::exp2 。
| (C++26 起) |
A) 为所有整数类型提供额外重载,将它们当做 double。 | (C++11 起) |
目录 |
[编辑]参数
n | - | 浮点数或整数 |
[编辑]返回值
如果没有发生错误,那么返回底数 2 指数 num(2n
)。
如果发生上溢导致的值域错误,那么返回 +HUGE_VAL
、+HUGE_VALF
或 +HUGE_VALL
。
如果发生下溢导致的值域错误,那么返回(舍入后的)正确结果。
[编辑]错误处理
报告 math_errhandling 中指定的错误。
如果实现支持 IEEE 浮点数算术(IEC 60559),那么
- 如果实参是 ±0,那么返回 1
- 如果实参是 -∞,那么返回 +0
- 如果实参是 +∞,那么返回 +∞
- 如果实参是 NaN,那么返回 NaN
[编辑]注解
额外重载不需要以 (A) 的形式提供。它们只需要能够对它们的整数类型实参 num 确保 std::exp2(num) 和 std::exp2(static_cast<double>(num)) 的效果相同。
对于整数指数,使用 std::ldexp 可能更好。
[编辑]示例
运行此代码
#include <cerrno>#include <cfenv>#include <cmath>#include <cstring>#include <iostream> // #pragma STDC FENV_ACCESS ON int main(){std::cout<<"exp2(4) = "<< std::exp2(4)<<'\n'<<"exp2(0.5) = "<< std::exp2(0.5)<<'\n'<<"exp2(-4) = "<< std::exp2(-4)<<'\n'; // 特殊值std::cout<<"exp2(-0) = "<< std::exp2(-0.0)<<'\n'<<"exp2(-Inf) = "<< std::exp2(-INFINITY)<<'\n'; // 错误处理errno=0;std::feclearexcept(FE_ALL_EXCEPT);constdouble inf = std::exp2(1024);constbool is_range_error =errno==ERANGE; std::cout<<"exp2(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";}
可能的输出:
exp2(4) = 16 exp2(0.5) = 1.41421 exp2(-4) = 0.0625 exp2(-0) = 1 exp2(-Inf) = 0 exp2(1024) = inf errno == ERANGE: Numerical result out of range 发生 FE_OVERFLOW
[编辑]参阅
(C++11)(C++11) | 返回 e 的给定次幂(ex) (函数) |
(C++11)(C++11)(C++11) | 返回 e 的给定次幂减 1(ex-1) (函数) |
(C++11)(C++11) | 将数乘以 2 的整数次幂 (函数) |
(C++11)(C++11)(C++11) | 给定数值的以 2 为底的对数(log2(x)) (函数) |
exp2 的 C 文档 |