Quantcast
Channel: How to check if a number is a power of 2 - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by Hans Brende for How to check if a number is a power of 2

$
0
0

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).


Viewing all articles
Browse latest Browse all 38

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>