Many answers solve this cleverly for integers, but here's how, using only basic floating-point operations, to solve it for double
!
const double HALF_EPS = 1.1102230246251565e-16; // 2^-53bool isPowerOf2(double n) { return ( n > 1e-292 ? n + n*HALF_EPS - n == 0 : n > 0 && n + n/HALF_EPS == n/HALF_EPS );}
For C# of course, you can simply use Double.isPow2
instead, but that doesn't translate to other languages. This answer will work for double-precision floating point numbers in any language, under the assumption that the rounding mode is the default IEEE 754 roundTiesToEven and subnormals aren't flushed to zero (if they are then you can simply increase 1e-292
to 1e-291
).
See my answer here for a complete proof of correctness (and why you should not use log2
to determine whether a number is a power of 2).