Skip to content

random.uniform(a, b) can overflow to values outside of [a, b] #134668

Closed as not planned
@tybug

Description

@tybug

Bug report

Bug description:

random.uniform can overflow to inf outside the range of [a, b] in some cases:

import random

random.uniform(-1e308, 1e308)  # math.inf

The implementation of random.uniform is:

def uniform(self, a, b):
    return a + (b - a) * self.random()

where (b - a) can overflow to math.inf: assert 1e308 * 2 == math.inf.

Since the docstring of random.uniform guarantees that the return value will be in the range [a, b], I would classify this as a bug.

I see a few solutions:

  • Error on overflow.
    • numpy does this: numpy.random.uniform(-1e308, 1e308) raises OverflowError.
  • Document that random.uniform may overflow to math.inf, even if b < math.inf.
  • Clamp out-of-bounds values (only if b - a == math.inf, for performance).

CPython versions tested on:

3.12

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

Labels

stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions