Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 511
Puna Avatar asked Nov 07 '25 06:11

Puna


1 Answers

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.

like image 186
Sash Sinha Avatar answered Nov 08 '25 21:11

Sash Sinha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!