I need to get soma random values between closed interval [0,1] rather than opened interval. Is there any way this can be done?

Is this ok?

2 Answers

Wyck On Best Solutions

You can use:

random.uniform(0, 1)

Note: When calling N = random.uniform(a, b), the behaviour is always that a <= N <= b but the end-point value b may or may not be included in the range depending on floating-point rounding.

See https://docs.python.org/3/library/random.html?highlight=uniform#random.uniform

Community On

First, try: import random (random.randint(0,10**6)*1.0 /10**6) This will give you full floating point precision. Otherwise, try:

import decimal

def randfloat():
    decimal.getcontext().prec = 10  # 10 decimal points enough?!
    return decimal.Decimal(0) + decimal.Decimal(random.uniform(0, 1))
# this should include both boundaries as float gets close enough to 1 to make decimal round

>>> decimal.Decimal(0) + decimal.Decimal(0.99999999999)

while uniform() apparently guarantees the inclusion of the lower boundary