我需要在闭区间[0,1]之间获得soma随机值而不是打开区间。有什么办法可以做到吗?
这个可以吗?
您可以使用:
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
首先,尝试: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()显然保证包含下边界