log2 not found in my math.h?

后端 未结 5 917
野的像风
野的像风 2020-12-01 15:25

I\'m using a fairly new install of Visual C++ 2008 Express.

I\'m trying to compile a program that uses the log2 function, which was found by including using Eclipse

5条回答
  •  被撕碎了的回忆
    2020-12-01 16:20

    Note that:

    log2(x) = log(x) * log(e)

    where log(e) is a constant. math.h defines M_LOG2E to the value of log(e) if you define _USE_MATH_DEFINES before inclusion of math.h:

    #define _USE_MATH_DEFINES // needed to have definition of M_LOG2E 
    #include 
    
    static inline double log2(double n)
    {
        return log(n) * M_LOG2E;
    }
    

    Even though usual approach is to do log(n)/log(2), I would advise to use multiplication instead as division is always slower especially for floats and more so on mobile CPUs. For example, on modern Intel CPUs the difference in generated code in just one instruction mulsd vs divsd and according to Intel manuals we could expect the division to be 5-10 times slower. On mobile ARM cpus I would expect floating point division to be somewhere 10-100 slower than multiplication.

    Also, in case if you have compilation issues with log2 for Android, seems like log2 is available in headers starting from android-18:

    #include 
    #if __ANDROID_API__ < 18
    static inline double log2(double n)
    {
        return log(n) * M_LOG2E;
    }
    #endif
    

提交回复
热议问题