Please, can someone help me with how to calculate a simple log2 in C? I tried with this code, but it does not work:
printf( "log( %f ) = %f\n", x, log2(x) );
Please, can someone help me with how to calculate a simple log2 in C? I tried with this code, but it does not work:
printf( "log( %f ) = %f\n", x, log2(x) );
#include <stdio.h>
#include <math.h>
int main() {
double x = 42.0;
printf( "log( %f ) = %f\n", x, log2(x) );
return 0;
}
OUTPUT
% ./a.out
log( 42.000000 ) = 5.392317
%
You can also create a helper function which converts to any log base you wish:
Something like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double
my_log(double x, int base) {
return log(x) / log(base);
}
int
main(void) {
double x = 42.0;
printf("log(%f) = %f\n", x, my_log(x, 2));
return 0;
}
Compiled with:
gcc -Wall -o logprog logprog.c -lm
Output:
log(42.000000) = 5.392317