python-3.x - 如何在闭区间[0,1]之间生成随机数?
问题描述
我需要在封闭区间 [0,1] 而不是开放区间之间获取 soma 随机值。有什么办法可以做到这一点?
这个可以吗?
解决方案
首先,尝试: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() 显然保证包含下边界
推荐阅读
- ubuntu-16.04 - 为什么控制台中的节点名称与 .launch 文件中的不同?
- postgresql - 从 PostGIS 点获取纬度/经度
- python - 如何将“对话”输出流式传输到标准输出?
- reactjs - 如何设置 react-admin Datagrid 的标题?
- html - 为什么最后一个 li 项目出现在父容器之外?
- swift - 如何在 SwiftUI 列表中显示领域结果?
- visible - anylogic 如何设置端口在上层可见 false
- html - 如何在不显示空格的情况下使用 CSS 在 HTML 中对齐元素(部分与标题)
- algorithm - 在滑动窗口中查找第二大元素
- javascript - 为什么我的 Promise reducer 模式会打乱订单?