An interesting question which I've never specifically considered before.
Some observations:
Log[8]/Log[2] // FullSimplify
Log2[8]
Log[2, 8]
3
3
3
And @@ IntegerQ /@ Log2[2^Range[50000]]
And @@ Table[IntegerQ@Log2[2^RandomInteger[5*^8]], {500}]
True
True
Mathematica documentation explicitly states:
Log2
gives exact integer or rational number results when possible.
Also for Log
:
Log
gives exact rational number results when possible.
For certain special arguments, Log
automatically evaluates to exact values.
I think that based on the combination of the empirical result and the statements in the documentation that it is safe to assume that Log2
will return an integer when given a 2^n number.
As far as how this is determined the Implementation Notes say only:
Log and inverse trigonometric functions use Taylor series and functional relations.
which I'm not sure applies.
Timings of Log2
compared to J. M.'s lovely bit-level test:
Do[IntegerQ @ Log2 @ n, {n, 1*^7}] // AbsoluteTiming // First
Do[BitAnd[n, n - 1] == 0, {n, 1*^7}] // AbsoluteTiming // First
15.9120279
6.4116112
And now vectorized:
a = Range@1*^6;
Position[Log2@a, _Integer, {1}] // AbsoluteTiming // First
Position[BitAnd[a, a - 1], 0] // AbsoluteTiming // First
1.4196025
0.0468001
Integer
by applyingN
. TryLog[2, 8]//N
to see that you don't get anInteger
either. $\endgroup$