Search code examples
python

When using random.uniform(a,b), is b inclusive or exclusive?


I was exploring the random module and can't find a correct answer to whether b is inclusive or exclusive in random.uniform(a, b).

In a code like random.uniform(0, 1), some answers say 1 is included while others say 1 is never produced. What's the correct answer?


Solution

  • The documentation for random.uniform(a, b) suggests that you may encounter cases where the upper limit b is included in the range due to how floating-point numbers are represented, but it's not guaranteed:

    Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

    The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random().

    So sometimes the upper limit b may be included, and sometimes it may not be.