python random_标准库中python的random.random()的范围

其他的答案已经澄清了1不在范围之内,但是出于好奇,我决定看看源代码,看看它是如何精确计算的。

可以找到CPython源here/* random_random is the function named genrand_res53 in the original code;

* generates a random number on [0,1) with 53-bit resolution; note that

* 9007199254740992 == 2**53; I assume they're spelling "/2**53" as

* multiply-by-reciprocal in the (likely vain) hope that the compiler will

* optimize the division away at compile-time. 67108864 is 2**26. In

* effect, a contains 27 random bits shifted left 26, and b fills in the

* lower 26 bits of the 53-bit numerator.

* The orginal code credited Isaku Wada for this algorithm, 2002/01/09.

*/

static PyObject *

random_random(RandomObject *self)

{

unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;

return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));

}

因此,函数有效地生成m/2^53,其中0 <= m < 2^53是一个整数。由于浮点数通常有53位精度,这意味着在[1/2,1]范围内,将生成所有可能的浮点数。对于接近0的值,它跳过一些可能的浮点值以提高效率,但生成的数字在范围内均匀分布。由random.random生成的最大可能数正是

0.999999999999988897769753748434595763683319091796875

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值