C
数值 | Numerics

log2

log2, log2f, log2l

在头文件中定义
float log2f( float arg (1)(since C99)
double log2( double arg (2)(since C99)
long double log2l( long double arg (3)(since C99)
Defined in header <tgmath.h>
#define log2( arg )(4)(since C99)

1-3)计算基数的2对数arg

4)类型 - 通用宏:如果arg有类型long doublelog2l被调用。否则,如果arg有整数类型或类型doublelog2则调用。否则,log2f被调用。

参数

arg-浮点值

返回值

如果没有发生错误,基极- 2对数arg(日志

2(arg)或lb(arg))。

如果发生域错误,则返回实现定义的值(NaN,如果支持)。

如果发生极错误-HUGE_VAL-HUGE_VALF-HUGE_VALL返回。

错误处理

按照math_errhandling中的指定报告错误。

如果arg小于零,则会发生域错误。

如果arg为零,则可能出现极点错误。

如果实现支持IEEE浮点运算(IEC 60559),

  • 如果参数为±0,则返回-∞并FE_DIVBYZERO引发。

笔记

对于整数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

参考

  • C11标准(ISO / IEC 9899:2011):