Reference · Math
math.log2
signature
math.log2(num) -> floatWhat it does
The logarithm of a number to base 2, as a float, as Python's math.log2. It is exact
for a power of two, and elsewhere a digit closer than math.log(x, 2), which divides
two logarithms. The number must be
above zero.
Examples
print(math.log2(8), math.log2(1024), math.log2(0.5))print(math.log2(10), math.log2(3))output
3.0 10.0 -1.03.321928094887362 1.584962500721156Edge cases
- A power of two gives a whole float:
math.log2(1024)is10.0. For other numbersmath.log(x, 2)can differ in the last digit. - A number between
0and1gives a negative answer; the smallest positive float is fine. infgivesinf,NaNgivesNaN.- The number of bits in a positive int is
math.floor(math.log2(n)) + 1.
print(math.log2(1024), math.log(1024, 2))print(math.log2(10), math.log(10, 2))print(math.log2(0.25), math.log2(5e-324))print(math.log2(math.inf), math.log2(math.nan))print(math.floor(math.log2(1024)) + 1, math.floor(math.log2(1023)) + 1)output
10.0 10.03.321928094887362 3.3219280948873626-2.0 -1074.0inf NaN11 10Errors
Zero or a negative number is a runtime error (a domain error), not an error value: it
stops the request, and ?? does not catch it. A value that is not a number is a
runtime error too.
this one fails
print(math.log2(0))output
line 1: `math.log2`: math domain error (0)this one fails
print(math.log2(-8))output
line 1: `math.log2`: math domain error (-8)Chaining
print(256 | math.log2)print([1, 2, 4, 8] | map(math.log2))print(10 | math.exp2 | math.log2)output
8.0[0.0, 1.0, 2.0, 3.0]10.0See also
math.log, math.log10, math.exp2, math.frexp
Thread
Thread 0 posts
On math.log2(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo