log2, log2f, log2l
来自 cppreference.cn
定义于头文件 <math.h> |
||
float log2f( float arg ); |
(1) | (自 C99 起) |
double log2( double arg ); |
(2) | (自 C99 起) |
long double log2l( long double arg ); |
(3) | (自 C99 起) |
定义于头文件 <tgmath.h> |
||
#define log2( arg ) |
(4) | (自 C99 起) |
1-3) 计算 arg 的底数为 2 的对数。
4) 类型泛型宏:如果
arg
的类型为 long double,则调用 log2l
。否则,如果 arg
具有整数类型或类型 double,则调用 log2
。否则,调用 log2f
。内容 |
[编辑] 参数
arg | - | 浮点数值 |
[编辑] 返回值
如果没有错误发生,则返回 arg 的底数为-2 的对数 (arg
) (log2(arg) 或 lb(arg))。
如果发生域错误,则返回实现定义的值(如果支持,则为 NaN)。
如果发生极点错误,则返回 -HUGE_VAL、-HUGE_VALF
或 -HUGE_VALL
。
[编辑] 错误处理
错误按照 math_errhandling
中的规定报告。
如果 arg
小于零,则发生域错误。
如果 arg
为零,则可能发生极点错误。
如果实现支持 IEEE 浮点算术 (IEC 60559),
- 如果参数为 ±0,则返回 -∞ 并引发 FE_DIVBYZERO。
- 如果参数为 1,则返回 +0
- 如果参数为负数,则返回 NaN 并引发 FE_INVALID。
- 如果参数为 +∞,则返回 +∞
- 如果参数为 NaN,则返回 NaN
[编辑] 注释
对于整数 arg
,二进制对数可以解释为输入中最高有效位 1 的从零开始的索引。
[编辑] 示例
运行此代码
#include <stdio.h> #include <math.h> #include <float.h> #include <errno.h> #include <fenv.h> // #pragma STDC FENV_ACCESS ON int main(void) { printf("log2(65536) = %f\n", log2(65536)); printf("log2(0.125) = %f\n", log2(0.125)); printf("log2(0x020f) = %f (highest set bit is in position 9)\n", log2(0x020f)); printf("base-5 logarithm of 125 = %f\n", log2(125)/log2(5)); // special values printf("log2(1) = %f\n", log2(1)); printf("log2(+Inf) = %f\n", log2(INFINITY)); //error handling errno = 0; feclearexcept(FE_ALL_EXCEPT); printf("log2(0) = %f\n", log2(0)); if(errno == ERANGE) perror(" errno == ERANGE"); if(fetestexcept(FE_DIVBYZERO)) puts(" FE_DIVBYZERO raised"); }
可能的输出
log2(65536) = 16.000000 log2(0.125) = -3.000000 log2(0x020f) = 9.041659 (highest set bit is in position 9) base-5 logarithm of 125 = 3.000000 log2(1) = 0.000000 log2(+Inf) = inf log2(0) = -inf errno == ERANGE: Numerical result out of range FE_DIVBYZERO raised
[编辑] 参考
- C17 标准 (ISO/IEC 9899:2018)
- 7.12.6.10 log2 函数 (p: 179)
- 7.25 类型泛型数学 <tgmath.h> (p: 272-273)
- F.10.3.10 log2 函数 (p: 381)
- C11 标准 (ISO/IEC 9899:2011)
- 7.12.6.10 log2 函数 (p: 246)
- 7.25 类型泛型数学 <tgmath.h> (p: 373-375)
- F.10.3.10 log2 函数 (p: 522)
- C99 标准 (ISO/IEC 9899:1999)
- 7.12.6.10 log2 函数 (p: 226)
- 7.22 类型泛型数学 <tgmath.h> (p: 335-337)
- F.9.3.10 log2 函数 (p: 459)
[编辑] 参见
(C99)(C99) |
计算自然对数(底为-e 的对数) (ln(x)) (函数) |
(C99)(C99) |
计算常用对数(底为-10 的对数) (log10(x)) (函数) |
(C99)(C99)(C99) |
计算 1 加上给定数字的自然对数(底为-e 的对数) (ln(1+x)) (函数) |
(C99)(C99)(C99) |
计算 2 的给定次幂 (2x) (函数) |
log2 的 C++ 文档
|