This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author rhettinger fredrikj, loewis, mark.dickinson, pitrou, rhettinger, skip.montanaro, terry.reedy, vstinner 2008-12-16.19:44:02 4.884475e-10 No <1229456644.39.0.0274303060729.issue3439@psf.upfronthosting.co.za>
Content
Of course, the name should have been bit_length() instead of numbits().

For the code equivalent, I'm aiming for something less process oriented
and more focused on what it does.  bit_length IS the number of bits in a
binary representation without the sign or leading zeroes -- that
definition IS a correct mental picture and does not require special
cases for zero or for negatives.

The purpose of the code equivalent is not efficiency or beauty; it to
help communicate was a function does.  If you want it to be more
beautiful, it can be broken into multiple lines.

I don't think you gain ANY explanatory power with code that says:
bit_length is the number of right-shifts (or floor divisions by two) of
the absolute value of a number until that number becomes zero.  Tell
that description to a high school student and prepare for a blank stare.

FWIW, I think having a mental picture that was too process oriented was
behind last night's mistake of thinking the (16).bit_length() was 5
instead of 4.  I theorize that error wouldn't have occurred if the
mental picture was of len('10000') instead of power-of-two mental model
where people (including some of the commenter here) tend to get the edge
cases wrong.

It would be better to have no code equivalent at all than to present the
repeated //2 method as a definition.  That is a process, but not a
useful mental picture to help explain what bit_length is all about.
Think about it, bit_length() is about the length in bits of a binary
representation -- any code provided needs to translate directly to that
definition.

def bit_length(x):
'''Length of a binary representation without the sign or leading zeroes:

>>> (-37).numbits()
6
'''

s = bin(x)          # binary representation:  bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and sign
return len(s)
History
Date User Action Args
2008-12-16 19:44:04rhettingersetrecipients: + rhettinger, loewis, skip.montanaro, terry.reedy, mark.dickinson, pitrou, vstinner, fredrikj
2008-12-16 19:44:04rhettingersetmessageid: <1229456644.39.0.0274303060729.issue3439@psf.upfronthosting.co.za>