Binary-scale calculations
Convert powers-of-two quantities into exponents, such as determining bit widths or binary scales.
NumPy · Function
Computes the base-2 logarithm of each input value. It is a NumPy ufunc that supports scalar and array inputs, with standard controls for output storage, masking, casting, dtype, and subclasses.
numpy.log2 applies the base-2 logarithm element by element to its input. It accepts scalars and array-like values, supports optional output storage and masked evaluation, and returns a scalar for scalar input or an array for array input.
numpy.log2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True [, signature])| Name | Type | Description |
|---|---|---|
x | array_like | Input value or array. |
out | ndarray, None, or tuple of ndarray and None | Optional output destination. |
where | array_like of bool | Boolean mask selecting where the result is computed. |
casting | {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional | Casting rule for operands. |
order | {‘K’, ‘A’, ‘C’, ‘F’}, optional | Memory layout order for the result. |
dtype | dtype, optional | Output data type. |
subok | bool, optional | Whether to return subclasses of input arrays. |
signature | None or str, optional | Optional generalized ufunc signature. |
ndarray: Base-2 logarithm of x; this is a scalar if x is a scalar.
out, where, casting, order, dtype, and subok.out to write computed values into an existing destination.import numpy as np
x = np.array([1, 2, 4, 16])
y = np.log2(x)
print(y) # [0. 1. 2. 4.]Computes the base-2 logarithm element by element.
Convert powers-of-two quantities into exponents, such as determining bit widths or binary scales.
Transform positive numeric arrays when a base-2 logarithmic scale is needed.
Compute complex logarithms using NumPy's documented principal-value convention.
numpy.log2 compute, and what kind of operation is it?np.log2(x) computes the base-2 logarithm of x element by element. It is a NumPy ufunc, so it works with scalars and arrays.
Follow-up: What happens for a scalar input? The result is a scalar rather than an ndarray.
np.log2 return for powers of two and zero?For an array such as [0, 1, 2, 16], the results are [-inf, 0., 1., 4.]. Zero therefore produces negative infinity in the documented example.
Follow-up: How can computation be restricted to selected elements? Supply a Boolean where mask and optionally an out array.
numpy.log2 expose?The function accepts out for placing results into an existing destination and where for selecting where the ufunc is evaluated. Other ufunc controls include casting, order, dtype, and subok.
Follow-up: Why might out be useful? It can avoid allocating a separate result array when writing into a prepared destination is appropriate.
numpy.lognumpy.log10numpy.log1pnumpy.emath.log2