Issue
I want to find the number of bits necessary to represent an unsigned numpy integer (or each element in an array of integers) in binary, in the same way the python's int.bit_length()
does, but it seems that numpy has no equivalent function.
For example:
>>> int(0b1000).bit_length()
4
>>> np.uint8(0b1000).bit_length()
AttributeError: 'numpy.uint8' object has no attribute 'bit_length'
Can anyone help me find the correct function? My current approach is to convert each array element to a python int to find the bit length, which seems like an awful option, for speed and clarity:
np.vectorize(lambda np_int: int(np_int).bit_length())
Solution
You can take the ceiling of the log2 of your array.
import numpy as np
x = np.random.randint(0, 100, size=30)
x
# returns:
array([92, 7, 53, 24, 85, 53, 78, 52, 99, 91, 79, 40, 82, 34, 18, 26, 20,
7, 47, 38, 78, 50, 15, 12, 54, 3, 91, 82, 22, 90])
np.ceil(np.log2(x)).astype(int)
# returns:
array([7, 3, 6, 5, 7, 6, 7, 6, 7, 7, 7, 6, 7, 6, 5, 5, 5, 3, 6, 6, 7, 6,
4, 4, 6, 2, 7, 7, 5, 7])
Answered By - James
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.