Andreas H. - 1 year ago 49

C Question

What is an efficient method to calculate the integer part of the base 2 logarithm of a floating point number? Something like

`N = ceil( log2( f ))`

or

`N = floor( log2( f ))`

for floating point f. I guess this is possible to realize very efficiently somehow as one probably only needs access to the floating point exponent.

EDIT2: I am not primarily interested in

I need this for accuracy control of an algorithm where the parameter f is some tolerance and the log is needed to control the number of terms. Accurate calculation of the log is not important.

EDIT: this is not a duplicate of other the many other questions asking for the log2 of an

Answer Source

The standard library function `frexp`

does exactly that: it decomposes a double into an integer exponent and a normalized mantissa.

If you are content with the floor of the logarithm, rather than rounding the logarithm to the nearest integer, you are probably better off with the newer standard library function `ilogb`

.

Note that these two functions treat zeros and infinities differently, so they are not quite interchangeable.