Skip to content

random._randbelow soft fix with performance gain #132320

@dg-pb

Description

@dg-pb

Bug report

Bug description:

Simplest example.

def _randbelow_with_getrandbits(self, n):
    "Return a random int in the range [0,n).  Defined for n > 0."

    k = n.bit_length()
    r = self.getrandbits(k)  # 0 <= r < 2**k
    print(r)
    while r >= n:
        r = self.getrandbits(k)
        print(r)
    print('accepted')
    return r

Calling random._inst._randbelow(2) returns the following:

2
1
accepted

2
3
3
0
accepted

2
2
3
2
2
0
accepted

Changing the line to:

k = (n - 1).bit_length()

For most of cases it will not make a difference, but I suspect it is not so rare that people call randint/randrange with numbers 2**n and for all of these, this will keep failing 50% of the time.

CPython versions tested on:

3.14

Operating systems tested on:

macOS

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions