Quickly find the integer part of the base 2 logarithm

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

N = ceil( log2( f ))

or

N = floor( log2( f ))

for floating point f. I think it is possible to implement this very efficiently one way or another, since you probably only need access to the floating point metric.

EDIT2: I am not primarily interested in accuracy. I could tolerate an error of + -1. I have listed two options, as an example, because it would be possible to calculate cheaper than the other (but I do not know).

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

EDIT: this is not a duplicate of many other questions requiring a log2 integer argument (e.g. How to make an integer log2 () in C ++? ). This is a floating point argument and a completely different story. In particular, I need this for f <1, which is generally not possible with integer methods

+4
source share
3 answers

The standard library function frexpdoes just that: it decomposes the 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 working with the newer standard library function ilogb.

, -, .

+7

, frexp, , . C99 ++ ilogb, ,

int ilogb( float arg );
int ilogb( double arg );

(int)logb( arg )

, frexp. , frexp

floor(log2(arg)+1 

ilogb (arg)

floor(log2(arg))
+1

, little-endian float, ..

#include <stdio.h>

int main(void) {
    float f;
    unsigned i;
    unsigned *ip = (unsigned*)&f;

    printf("Enter a float: ");
    scanf("%f", &f);
    i = *ip;
    i = (i >> 23) & 0xFF;
    i -= 127;
    printf("%f %d\n", f, (int)i);
    return 0;
}

:

Enter a float: 0.125
0.125000 -3
0

Source: https://habr.com/ru/post/1653712/


All Articles