0

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) );
Will Tate
  • 33,439
  • 9
  • 77
  • 71
Jonahatan peña
  • 49
  • 1
  • 1
  • 6

2 Answers2

5
#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
%
cdlane
  • 40,441
  • 5
  • 32
  • 81
3

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
RoadRunner
  • 25,803
  • 6
  • 42
  • 75