Python Glossary Русский

Python 3.3+mathterm

math.log2

logarithms

Returns the base-2 logarithm. More accurate and faster than math.log(x, 2). Useful in binary-tree algorithms.

Syntax

math.log2(x)

Zero and negative inputs raise ValueError ("math domain error"), not -inf. For integers it is usually better to skip floats entirely: the floor of the base-2 logarithm is n.bit_length() - 1, and the power-of-two test is n > 0 and n & (n - 1) == 0. On very large integers the float version rounds and can be off right at a boundary; the integer tricks never are.

Examples

import math
print(math.log2(1))    # → 0.0
print(math.log2(2))    # → 1.0
print(math.log2(8))    # → 3.0
print(math.log2(1024)) # → 10.0
print(math.log2(3))    # → 1.584962...
print(math.log2(0.5))  # → -1.0

See also

Open in the full glossarydocs.python.orgReport an inaccuracy