1

gcc (4.8.1) and clang (3.4) compile my C++ program which uses std::log2(x). Is this standard compliant?

Walter
  • 44,150
  • 20
  • 113
  • 196
  • 2
    Why shouldn't it? Googling for this function reveals that [it's part of the C++ standard library](http://en.cppreference.com/w/cpp/numeric/math/log2) since C++11. If it wasn't part of the standard library, it would be undefined behavior to add it to the `std` namespace. In other words, there is no such thing as "extensions" to the standard library, speaking of the `std` namespace. – leemes Mar 13 '14 at 19:16
  • @leemes A conforming implementation isn't allowed to add names to the `std` namespace in any of the standard headers. A simple reason why is that if `foo` is not defined as part of the standard library, a user is allowed to define `foo` as a macro before including a standard header. If the header then attempts to define `foo` as (for example) a function, the macro would be expanded, and a valid program would be rejected. –  Mar 13 '14 at 19:31
  • @hvd I know that... I'm not sure why you say that. Did you want to add that to my comment or did you misunderstand what I wanted to say? ;) My point was: since it's not allowed to add things to `std` there is no such thing as an "extension" to the standard library, such as `log2` prior to C++11 when it was added. – leemes Mar 13 '14 at 19:57
  • @leemes I think I misunderstand your comment, then. "it would be undefined behavior to add it to the `std` namespace" came across as "programs are not allowed to define their own `std::log2`, therefore if an implementation does so, there is no conflict" –  Mar 13 '14 at 20:46

2 Answers2

4

It is now included in <cmath> header since C++11.

You can find more information here: std::log2

taocp
  • 23,276
  • 10
  • 49
  • 62
  • I was looking on this website, the its search function didn't (and for still doesn't) come up with this page when search for `std::log2` or `log2` :-( – Walter Mar 13 '14 at 19:45
  • @Walter Strange enough.Thanks for accepting the answer. – taocp Mar 13 '14 at 19:46
1

If you are using an earlier C++ compiler that doesn't have this function, you can use log(x) / log(2.0).

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • yes, I know, this will typically call `std::log()` twice. – Walter Mar 13 '14 at 19:46
  • 1
    @Walter you can always use a hard-coded constant for `log(2.0)` since it will never change. `0.693147180559945309` should work. – Mark Ransom Mar 13 '14 at 19:52
  • Does log2 have special handling for powers of two? I was encountering floating point errors with log(x) / log(2.0) but they resolved when I used log2. – SapphireSun Aug 12 '18 at 22:50
  • @SapphireSun I doubt that it treats powers of 2 differently from any other input, but it might have an algorithm that rounds differently. It's impossible to know without looking at your library's implementation. – Mark Ransom Aug 12 '18 at 23:44