在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).