如何在闭区间[0,1]之间生成随机数?

问题描述 投票:-1回答:2

我需要在闭区间[0,1]之间获得soma随机值而不是打开区间。有什么办法可以做到吗?

这个可以吗?

python-3.x random
2个回答
0
投票

您可以使用:

random.uniform(0, 1)

注意:调用N = random.uniform(a, b)时,行为始终是a <= N <= b,但终点值b可能包含也可能不包含在范围内,具体取决于浮点舍入。

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


0
投票

首先,尝试:import random (random.randint(0,10**6)*1.0 /10**6)这将为您提供完整的浮点精度。否则,请尝试:

导入小数

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)
Decimal('1.000000000')

而uniform()显然保证包含下边界

© www.soinside.com 2019 - 2024. All rights reserved.