首页 > 解决方案 > 如何在闭区间[0,1]之间生成随机数?

问题描述

我需要在封闭区间 [0,1] 而不是开放区间之间获取 soma 随机值。有什么办法可以做到这一点?

这个可以吗?

标签: python-3.xrandom

解决方案


首先,尝试: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() 显然保证包含下边界


推荐阅读