4

Here is my code.

#include <iostream>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include <cmath>
#include <functional>
using namespace std;
void main()
{
    cout<<log2(3.0)<<endl;

}

But above code gives error. Error code is : error C3861: 'log2': identifier not found. How can i calculate log2 using c++?

user2036891
  • 231
  • 3
  • 5
  • 11

5 Answers5

7

for example for log 3 in base 2

log (3) / log(2)

will do it.

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    cout << log(3.0) / log(2.0) << endl;

}
Hayri Uğur Koltuk
  • 2,970
  • 4
  • 31
  • 60
7

Using highschool mathematics:

log_y(x) = ln(x)/ln(y)

But I agree, that's a little strange that there's no such utility function out there. That's probably due to the almost-direct mapping of those functions to FPU..

However do not worry about using this 'expanded' way. The mathematics will not change. The formula will be valid for at least next few lifetimes.

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
4

The following code works with gcc compiler

#include <iostream>
#include<stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cmath> 
#include <functional>
using namespace std;
main()
{
    cout<<log2(3.0)<<endl;

}
banarun
  • 2,305
  • 2
  • 23
  • 40
3

This should be a general function for finding the log with a base of any given number

double log_base_n(double y, double base){
return log(y)/log(base);
}

so:

cout<<log_base_n(3.0,2.0);

ought to do the trick.

user1833028
  • 865
  • 1
  • 9
  • 18
  • https://www.khanacademy.org/math/algebra/logarithms-tutorial/logarithm_properties/v/change-of-base-formula should help explain WHY it works... – user1833028 Feb 14 '13 at 10:17
2

use log(3.0)/log(2.0). log2 is not included in C90.

double log_2( double n )  
{  
    return log(n) / log(2);  
}
Abhishek Thakur
  • 16,337
  • 15
  • 66
  • 97