Monday, December 11, 2017

C++11: std::log2()

C++11 the function std::log2(), which takes the log base 2 of its input parameter. Here is an example:

#include <cfloat>
#include <iostream>
using namespace std;

int main()
{
  cout << log2(pow(2.0, 10.0)) << " "; // 10
  cout << log2(pow(2.0,  5.0)) << " "; //  5
  cout << log2(pow(2.0,  2.0)) << " "; //  2
  cout << log2(pow(2.0,  1.0)) << " "; //  1
  cout << log2(pow(2.0,  0.0)) << " "; //  0

  cout << ( log(pow(2.0, 10.0)) / log(2) ) << " "; // 10

  cout << endl;
  return 0;
}
// Output: 10 5 2 1 0 10
Reference: http://en.cppreference.com/w/cpp/numeric/math/log2

No comments:

Post a Comment