New submission from Paul Sokolovsky <pfal...@users.sourceforge.net>:

Current docs for random.getrandbits() ( 
https://docs.python.org/3/library/random.html#random.getrandbits ) read 
(3.9.1rc1 at the top of the page):

Returns a Python integer with k random bits. This method is supplied with the 
MersenneTwister generator and some other generators may also provide it as an 
optional part of the API. When available, getrandbits() enables randrange() to 
handle arbitrarily large ranges.

So, based that it talks about "bits", it's easy to imagine that the result is 
unsigned. But it's interesting that it mentions "a Python integer", not even 
just "integer". And Python integers are known to be signed.

So I'd say, there's enough of ambiguity in there, and would be nice to 
explicitly specify that it's "unsigned (non-negative) Python integer".


If there's interest for the background of concern, some implementations may 
have "small" and "large" integers underlyingly (which used to be exposed at the 
user-level in Python2). "Small" integers would be cheaper, but of course, they 
would be signed. So, at certain value of getrandbits() parameter, there may be 
a temptation to use up a sign bit of a small integer, instead of going straight 
to allocating expensive large integer. It should be clear this is NOT a valid 
"optimization", and result should be always non-negative.

----------
messages: 382434
nosy: pfalcon
priority: normal
severity: normal
status: open
title: random.getrandbits: Should it be explicit that it returns 
unsigned/non-negative integer?
versions: Python 3.9

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue42559>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to