在python中,random.uniform()和random.random()有什么区别? [英] In python, what is the difference between random.uniform() and random.random()?

查看:162
本文介绍了在python中,random.uniform()和random.random()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中的random模块,random.uniform()random.random()有什么区别?它们都生成伪随机数,random.uniform() 从均匀分布生成数字,random.random() 生成下一个随机数.有什么区别?

In python for the random module, what is the difference between random.uniform() and random.random()? They both generate pseudo random numbers, random.uniform() generates numbers from a uniform distribution and random.random() generates the next random number. What is the difference?

推荐答案

random.random() 给你一个 [0.0, 1.0) 范围内的随机浮点数> (所以包括 0.0,但不包括 1.0,也称为半开放范围).random.uniform(a, b) 给你一个 [a, b] 范围内的随机浮点数,(四舍五入可能最终给你 b).

random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0 which is also known as a semi-open range). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where rounding may end up giving you b).

random.uniform()的实现 直接使用 random.random() :

def uniform(self, a, b):
    "Get a random number in the range [a, b) or [a, b] depending on rounding."
    return a + (b-a) * self.random()

random.uniform(0, 1)random.random() 基本相同(作为 1.0最接近 1.0 的浮点值仍然会给你 最接近 1.0 的浮点值,那里不可能出现舍入错误).

random.uniform(0, 1) is basically the same thing as random.random() (as 1.0 times float value closest to 1.0 still will give you float value closest to 1.0 there is no possibility of a rounding error there).

这篇关于在python中,random.uniform()和random.random()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆