At school we learned that $\log_b(x)=\log(x)/\log(b)$, which is implemented in Mathematica as Log[b, x], but the results are different.
Log[8]/Log[2] // N
returns
3. (* Real *)
while
Log[2, 8]
returns
3 (* Integer *)
If I want to validate the argument of my hadamardMatrix[] function as a power of 2:
hadamardMatrix[1] := {{1}}
hadamardMatrix[2] := {{1, 1}, {1, -1}}
hadamardMatrix[n_ /; IntegerQ[Log[2, n]]] :=
KroneckerProduct[hadamardMatrix[2], hadamardMatrix[n/2]]
How can I be sure that any Log[2, 2N] will always be regarded as integer?
Answer
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:
Log2gives exact integer or rational number results when possible.
Also for Log:
Loggives exact rational number results when possible.For certain special arguments,
Logautomatically 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
Comments
Post a Comment