python中0到1之间的随机数

时间:2015-10-27 03:59:11

标签: python random

我想要一个介于0和1之间的随机数,如0.3452。我使用了random.randrange(0, 1),但对我来说总是0。我该怎么办?

7 个答案:

答案 0 :(得分:132)

您可以使用random.uniform

import random
random.uniform(0, 1)

答案 1 :(得分:45)

random.random()正是这样做的

>>> import random
>>> for i in range(10):
...     print(random.random())
... 
0.908047338626
0.0199900075962
0.904058545833
0.321508119045
0.657086320195
0.714084413092
0.315924955063
0.696965958019
0.93824013683
0.484207425759

如果您想要真正的随机数,并涵盖范围[0,1]:

>>> import os
>>> int.from_bytes(os.urandom(8), byteorder="big") / ((1 << 64) - 1)
0.7409674234050893

答案 2 :(得分:10)

您可以尝试使用random.random()

  

random.random()返回下一个随机浮点数   范围[0.0,1.0)。

来自https://docs.python.org/2/library/random.html

答案 3 :(得分:4)

你可以使用numpy.random模块,你可以得到你想要的随机数字阵列

>>> import numpy as np
>>> np.random.random(1)[0]
0.17425892129128229
>>> np.random.random((3,2))
array([[ 0.7978787 ,  0.9784473 ],
       [ 0.49214277,  0.06749958],
       [ 0.12944254,  0.80929816]])
>>> np.random.random((3,1))
array([[ 0.86725993],
       [ 0.36869585],
       [ 0.2601249 ]])
>>> np.random.random((4,1))
array([[ 0.87161403],
       [ 0.41976921],
       [ 0.35714702],
       [ 0.31166808]])
>>> np.random.random_sample()
0.47108547995356098

答案 4 :(得分:4)

random.randrange(0,2)这个有效!

答案 5 :(得分:2)

<强> RTM

来自Python random模块的文档:

Functions for integers:

random.randrange(stop)
random.randrange(start, stop[, 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.

这就解释了为什么它只给你0,不是。 range(0,1)[0]。它从仅包含该值的列表中进行选择。

同样来自那些文档:

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

但如果您有意包含numpy标记,则可以使用np.random函数在一个调用中生成该范围内的许多随机浮点数。

答案 6 :(得分:-4)

我觉得我的变化更灵活。

str_Key           = ""
str_FullKey       = "" 
str_CharacterPool = "01234ABCDEFfghij~-)"
for int_I in range(64): 
    str_Key = random.choice(str_CharacterPool) 
    str_FullKey = str_FullKey + str_Key