代码改变世界

python模块学习之random

2013-11-13 20:46  youxin  阅读(329)  评论(0编辑  收藏  举报

模块源码:

Source code: Lib/random.py

文档:http://docs.python.org/2/library/random.html

常用方法:

random.random()

Return the next random floating point number in the range [0.0, 1.0).

random.randint(ab)包括b

Return a random integer N such that a <= N <= b.

 

random.uniform(ab)

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) *random().

用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: b <= n <= a。如果 a <b, 则 a <= n <= b。

print random.uniform(10, 20)
print random.uniform(20, 10)
#---- 结果(不同机器上的结果不一样)
#18.7356606526
#12.5798298022

 

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

这个写代码可能会用到。

random.randrange(stoprandom.randrange(startstop[step])

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

 

记住常用的就可以了。