log2, log2f, log2l
来自cppreference.com
| 在标头 <math.h> 定义
|
||
| |
(1) | (C99 起) |
| |
(2) | (C99 起) |
| |
(3) | (C99 起) |
| 在标头 <tgmath.h> 定义
|
||
| |
(4) | (C99 起) |
1-3) 计算
arg 的底 2 对数。4) 泛型宏:若
arg 拥有 long double 类型,则调用 log2l。否则,若 arg 拥有整数类型或 double 类型,则调用 log2。否则调用 log2f。参数
| arg | - | 浮点数 |
返回值
若不出现错误,则返回 arg 的底 2 对数(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));
// 特殊值
printf("log2(1) = %f\n", log2(1));
printf("log2(+Inf) = %f\n", log2(INFINITY));
// 错误处理
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 The log2 functions (第 179 页)
- 7.25 Type-generic math <tgmath.h> (第 272-273 页)
- F.10.3.10 The log2 functions (第 381 页)
- C11 标准(ISO/IEC 9899:2011):
- 7.12.6.10 The log2 functions (第 246 页)
- 7.25 Type-generic math <tgmath.h> (第 373-375 页)
- F.10.3.10 The log2 functions (第 522 页)
- C99 标准(ISO/IEC 9899:1999):
- 7.12.6.10 The log2 functions (第 226 页)
- 7.22 Type-generic math <tgmath.h> (第 335-337 页)
- F.9.3.10 The log2 functions (第 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++ 文档
| |