What is the log2 function in numpy?

In numpy, a library of the high-level programming language Python, we can use the log2 function to calculate the base 2 logarithm.

The numpy library must be imported to use the log2 function:

import numpy as np

Syntax

np.log2(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])= <ufunc 'log2'>

A universal function (ufunc) is a function that operates on ndarrays in an element-by-element fashion. The log2 method is a universal function.

Arguments

The log2 function only accepts the following arguments:

  • x: An array-like structure on the contents of which the log2 function will be applied.
  • out (optional): The function’s output is stored at this location.
  • where (optional): If set True, a universal function is calculated at this position.
  • casting (optional): This enables the user to decide how the data will be cast. If set as same_kind, safe casting will take place.
  • order (optional): This determines the memory layout of the output. For example, if set as K, the function reads data in the order they are written in memory.
  • dtype(optional): This is the data type of the array.
  • subok(optional): To pass subclasses, subokmust be set as True.

Return value

The log2 function returns an array of float values whose imaginary part lies in [-pi,pi].

If a number can not be represented as a real number or infinity, it returns nan, and the invalid floating point error flag is set. The log2 function has branch cuts at [-inf,0] and is continuous above it for complex input.

For real input, the log2 function returns real input. It treats the floating-point negative zero as an infinitesimal negative number, following the C99 standard.

If x is scalar, then return type is scalar.

Example

The following example demonstrates how to use the log2 function.

To use the log2 function, we first import the numpy library, which contains it.

import numpy as np
print(np.log2([0, 1, 4, 6]))
Copyright ©2024 Educative, Inc. All rights reserved